﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;
using System.Data.Common;
using System.Data.EntityClient;
using System.Transactions;
using System.IO;
using System.Xml;

using MINERP.DAL;
using MINERP.DAL.CustomerManage;
using MINERP.COM;
using MINERP.DAL.CommonDAL;
using MINERP.MODEL.InfoConfig;


namespace MINERP.BLL.CustomerManage
{
    public class StartOrderBLL
    {
        private StartOrderDAL SODAL = new StartOrderDAL();
        Common.WorkFlowListBLL workFlowListBll = new MINERP.BLL.Common.WorkFlowListBLL();

        public List<STShop> ListShop;

        #region 所有的产品集合
        /// <summary>
        /// 所有的产品集合
        /// </summary>
        public List<ProductInfo> GetProductList()
        {
            try
            {
                int delStatus = (int)COM.ProductStatus.Delete;
                ObjectQuery<Tb_Product> query = SODAL.GetProduct();
                List<ProductInfo> productList = new List<ProductInfo>();
                foreach (Tb_Product item in query.Where(p => p.Status == delStatus))
                {

                    ProductInfo pd = new ProductInfo();
                    pd.ProductID = item.ProuctId;
                    pd.ProductName = item.ProductName;
                    pd.Width = (float)item.Width;
                    pd.Height = (float)item.Height;
                    pd.PageNum = item.PageNum;
                    pd.ProductCategoryID = item.Tb_PorductCategory.ProductCategoryId;
                    pd.ProductCategoryName = item.Tb_PorductCategory.ProductCategoryName;
                    pd.ProductTypeCode = item.tb_ProductType.ProductTypeCode;      //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印
                    //pd.ProductRemark = item.ProductDes;
                    pd.PaperTypeID = item.paperType.PaperTypeID;
                    pd.PaperFaceID = item.paperFace.PaperFaceID;
                    pd.PaperTypeName = item.paperType.Name;
                    pd.PaperFaceName = item.paperFace.Name;
                    pd.ZJCode = item.mnemonicCode.ToUpper();
                    productList.Add(pd);
                }
                return productList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取商户特有的产品集合
        /// <summary>
        /// 获取商户特有的产品集合
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<ProductInfo> GetShopProductList(int shopId)
        {
            try
            {
                List<ProductInfo> products = new List<ProductInfo>();
                int delStatus = (int)COM.ProductStatus.Delete;

                /*
                List<Shop_Product_Price> shopProducts = SODAL.GetProductShop2(shopId);
                foreach (Shop_Product_Price item in shopProducts)
                {
                    ProductInfo pd = new ProductInfo();
                    if (!item.Tb_ProductReference.IsLoaded)
                        item.Tb_ProductReference.Load(MergeOption.OverwriteChanges);
                    if (item.Tb_Product.Status == delStatus)    //产品已被删除
                    {
                        continue;
                    }
                    pd.ProductID = item.Tb_Product.ProuctId;
                    pd.ProductName = item.Tb_Product.ProductName;
                    pd.Width = (float)item.Tb_Product.Width;
                    pd.Height = (float)item.Tb_Product.Height;
                    pd.PageNum = item.Tb_Product.PageNum;
                    if (!item.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        item.Tb_Product.Tb_PorductCategoryReference.Load(MergeOption.OverwriteChanges);
                    SODAL.RefreshPhotoinfo(item.Tb_Product);
                    pd.ProductCategoryID = item.Tb_Product.Tb_PorductCategory.ProductCategoryId;
                    pd.ProductCategoryName = item.Tb_Product.Tb_PorductCategory.ProductCategoryName;
                    if (!item.Tb_Product.tb_ProductTypeReference.IsLoaded)
                        item.Tb_Product.tb_ProductTypeReference.Load(MergeOption.OverwriteChanges);
                    pd.productTypeRemark = item.Tb_Product.tb_ProductType.ProductTypeCode;      //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印
                    //pd.ProductRemark = item.ProductDes;
                    pd.PaperFaceID = item.paperFace.PaperFaceID;
                    pd.PaperTypeID = item.paperType.PaperTypeID;
                    pd.PaperTypeName = item.paperType.Name;
                    pd.PaperFaceName = item.paperFace.Name;
                    pd.ZJCode = item.Tb_Product.mnemonicCode;
                    products.Add(pd);
                }*/

                DataTable dt = SODAL.GetProductShop(shopId);
                List<ProductInfo> orderProducts = products.OrderBy(p => p.Width).ToList();
                DataTable dtPC = SODAL.GetProductCommonChange();
                List<ProductCommonItem> listpci = new List<ProductCommonItem>();
                foreach (DataRow dw in dtPC.Rows)
                {
                    ProductCommonItem pc = new ProductCommonItem();
                    pc.CommonID = Convert.ToInt32(dw["CommonChargeItemId"]);
                    pc.ProductID = Convert.ToInt32(dw["Productid"]);
                    pc.ItemName = Convert.ToString(dw["ItemName"]);
                    listpci.Add(pc);
                }
                foreach (DataRow r in dt.Rows)
                {
                    if (Convert.ToInt32(r["Status"]) == delStatus)
                        continue;
                    ProductInfo pd = new ProductInfo();
                    pd.ProductID = Convert.ToInt32(r["ProductID"]);
                    pd.ProductName = r["ProductName"].ToString();
                    pd.Width = Convert.ToSingle(r["Width"]);
                    pd.Height = Convert.ToSingle(r["Height"]);
                    pd.PageNum = Convert.ToInt32(r["PageNum"]);
                    pd.ProductCategoryID = Convert.ToInt32(r["ProductCategoryID"]);
                    pd.ProductCategoryName = r["ProductCategoryName"].ToString();
                    pd.ProductTypeCode = Convert.ToInt32(r["productTypeCode"]);      //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印 5不含照片产品
                    pd.PaperFaceID = Convert.ToInt32(r["PaperFaceID"]);
                    pd.PaperTypeID = Convert.ToInt32(r["PaperTypeID"]);
                    pd.PaperTypeName = r["PaperTypeName"].ToString();
                    pd.PaperFaceName = r["PaperFaceName"].ToString();
                    pd.ZJCode = r["ZJCode"].ToString();
                    if (r["UsedTimes"] != DBNull.Value)
                        pd.UsedTimes = Convert.ToInt32(r["UsedTimes"]);

                    pd.ProductCommonBing = listpci.Where(pc => pc.ProductID == pd.ProductID).ToList();
                    products.Add(pd);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取待开单总目录
        /// <summary>
        /// 获取待开单总目录
        /// </summary>
        /// <returns></returns>
        public string GetStartOrderPath()
        {
            try
            {
                string startOrderPath = SODAL.GetStartOrderPath();
                return startOrderPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 订单在服务器上的存放总路径
        /// <summary>
        /// 订单在服务器上的存放总路径
        /// </summary>
        /// <returns></returns>
        public string GetOrderStorePath()
        {
            try
            {
                string orderStorePath = SODAL.GetOrderStorePath();
                return orderStorePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 订单在服务器上的存放总路径(编辑订单)
        /// <summary>
        /// 订单在服务器上的存放总路径(编辑订单)
        /// </summary>
        /// <returns></returns>
        public string GetOrderStorePathEdit()
        {
            try
            {
                string orderStorePath = SOEDAL.GetOrderStorePath();
                return orderStorePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion



        #region 产品DT
        public DataTable CreateProductDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ProductID", typeof(int));
            dt.Columns.Add("ProductName", typeof(string));
            dt.Columns.Add("Width", typeof(float));
            dt.Columns.Add("Height", typeof(float)); ;
            dt.Columns.Add("PageNum", typeof(int));
            dt.Columns.Add("ProductCategoryID", typeof(int));
            dt.Columns.Add("ProductCategoryName", typeof(string));
            dt.Columns.Add("ProductRemark", typeof(string));
            dt.Columns.Add("IsNeedDesign", typeof(bool));
            return dt;
        }
        #endregion

        #region 获取所有产品的默认流程
        /// <summary>
        /// 获取所有产品的默认流程
        /// </summary>
        /// <returns></returns>
        public List<STProductTech> GetProductFlow()
        {
            try
            {
                List<STProductTech> productTechList = new List<STProductTech>();
                List<Tb_FlowTemplate> query = SODAL.GetProductFlow();
                foreach (Tb_FlowTemplate item in query)
                {
                    STProductTech pt = new STProductTech();
                    item.Tb_ProductReference.Load();
                    pt.ProductID = item.Tb_Product.ProuctId;
                    item.tb_TechReference.Load();
                    pt.TechID = item.tb_Tech.TechId;
                    pt.TechName = item.tb_Tech.TechName;
                    pt.WorkOrder = item.WorkOrder;
                    pt.IsNessesary = item.IsNecessery;
                    productTechList.Add(pt);
                }
                return productTechList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有的节点信息
        /// <summary>
        /// 获取所有的节点信息
        /// </summary>
        /// <returns></returns>
        public List<STProductTech> GetAllTech()
        {
            try
            {
                List<tb_Tech> query = SODAL.GetAllTech();
                List<STProductTech> techs = new List<STProductTech>();
                foreach (tb_Tech tech in query)
                {
                    STProductTech st = new STProductTech();
                    st.TechID = tech.TechId;
                    st.TechName = tech.TechName;
                    st.NeedTime = Convert.ToDouble(tech.NeedTime);
                    techs.Add(st);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有纸型
        /// <summary>
        /// 获取所有纸型
        /// </summary>
        /// <returns></returns>
        public List<STPaperType> GetPaperType()
        {
            try
            {
                List<STPaperType> list = new List<STPaperType>();
                List<paperType> query = SODAL.GetPaperType();
                foreach (paperType item in query)
                {
                    STPaperType ptype = new STPaperType();
                    ptype.PaperTypeID = item.PaperTypeID;
                    ptype.PaperTypeName = item.Name;
                    list.Add(ptype);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //public List<STPaperType> GetShopPaperType(int inShopId)
        //{
        //    List<STPaperType> paperType = new List<STPaperType>();
        //    using (newSampleYPDBEntities db = new newSampleYPDBEntities())
        //    {
        //        Shop currShop = db.Shop.FirstOrDefault(p=>p.ShopId==inShopId);
        //        currShop.Shop_Paper_Price.Load();
        //        foreach (Shop_Paper_Price spp in currShop.Shop_Paper_Price)
        //        {
        //            spp.paperTypeReference.Load();
        //            paperType pt=new paperType();

        //            paperType.Add(new STPaperType() { PaperTypeID = pt.PaperTypeID, PaperTypeName=pt.Name});
        //        }

        //    }
        //}
        #endregion

        #region 获取所有纸面
        /// <summary>
        /// 获取所有纸面
        /// </summary>
        /// <returns></returns>
        public List<STPaperFace> GetPaperFace()
        {
            try
            {
                List<STPaperFace> list = new List<STPaperFace>();
                List<paperFace> query = SODAL.GetPaperFace();
                foreach (paperFace item in query)
                {
                    STPaperFace pface = new STPaperFace();
                    pface.PaperFaceID = item.PaperFaceID;
                    pface.PaperFaceName = item.Name;
                    list.Add(pface);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有的商户 (页面Load时须执行此方法)
        /// <summary>
        /// 获取所有的商户 (页面Load时须执行此方法)
        /// </summary>
        /// <returns></returns>
        public List<STShop> GetShopList()
        {
            try
            {
                List<Shop> query = SODAL.GetShopList().OrderBy(p => p.shopName).ToList();
                ListShop = new List<STShop>();
                foreach (Shop s in query)
                {
                    STShop s2 = new STShop();
                    s2.ShopID = s.ShopId;
                    s2.ShopName = s.shopName;
                    s2.ShopKeeper = s.shopKeeper;
                    s2.Tel1 = s.Tel1;
                    s2.Tel2 = s.Tel2;
                    s2.Address = s.address;
                    if (s.PaperFaceId == null)
                        s2.paperFaceId = 0;
                    else
                        s2.paperFaceId = (int)s.PaperFaceId;
                    if (s.PaperTypeId == null)
                        s2.paperTypeId = 0;
                    else
                        s2.paperTypeId = (int)s.PaperTypeId;
                    if (s.Priority == null)
                        s2.Priority = 0;
                    else
                        s2.Priority = (int)s.Priority;
                    //s2.UnitPrice = s.unitPrice;
                    ListShop.Add(s2);
                }
                return ListShop;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 判断订单包是否已存在
        /// <summary>
        /// 判断订单包是否已存在
        /// </summary>
        /// <param name="bagCode"></param>
        /// <returns></returns>
        public bool IsOrderBagExist(string bagCode)
        {
            try
            {
                return SODAL.IsOrderBagExist(bagCode);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 开单
        /// <summary>
        /// 开单
        /// </summary>
        public void AddOrderBag(List<ProductInfo> ListProduct, int OrderID, string OrderBagCode, string orderName, int orderPriority, int shopID, string shopName, DateTime orderTime, DateTime preCompleteTime, string orderRemark, int userId)
        {
            List<WorkOrderFlowList> startOrderFlows = new List<WorkOrderFlowList>();       //开单流程，插入开单信息后统计开单员业绩
            List<string> PhotoTemps = new List<string>();       //开单断网后照片复位
            List<string> MovedTarPaths = new List<string>();    //上次断网时已移动了的照片路径
            List<orderInfo> addProductInfo = new List<orderInfo>();     //新插入的产品集合
            List<photoInfo> addPhotoInfo = new List<photoInfo>();       //新插入的照片集合 
            DateTime realOrderTime = GetServerTime();                   //真实开单时间取服务器的时间
            preCompleteTime = realOrderTime.Add(preCompleteTime - orderTime);   //真实预计完成时间=真实开单时间+(本地预计完成时间-本地开单时间)
            orderTime = realOrderTime;
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            Tb_OrderBag Order = null;
            int connectTime = 0;
            //double orderAreas = 0;
            try
            {
                try
                {
                    SODAL.DataEntites.Connection.Open();
                }
                catch (Exception ex)
                {
                    connectTime++;
                    if (connectTime == 1)
                    {
                        AddOrderBag(ListProduct, OrderID, OrderBagCode, orderName, orderPriority, shopID, shopName, orderTime, preCompleteTime, orderRemark, userId);
                        return;
                    }
                    else
                    {
                        throw ex;
                    }
                }
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {
                    //DAL.newSampleYPDBEntities refEntities = new newSampleYPDBEntities();
                    List<paperFace> ListPaperFace = null;
                    List<paperType> ListPaperType = null;

                    List<string> productPaths = new List<string>();             //保存产品的路径,出错后删除复制的产品信息
                    ListPaperFace = SODAL.GetPaperFace();       //所有纸型
                    ListPaperType = SODAL.GetPaperType();       //所有纸面

                    string SaveTotalPath = GetOrderStorePath();                 //照片在服务器上的总路径

                    string DelPath = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //如果出错删除该目录

                    try
                    {
                        //读上次断网时已移动到“已开单”下的照片路径
                        XmlDocument doc = new XmlDocument();
                        if (File.Exists("XmlTarPath.xml"))
                        {
                            doc.Load("XmlTarPath.xml");
                            XmlNodeList nodeList = doc.GetElementsByTagName("TarPath");
                            foreach (XmlNode node in nodeList)
                            {
                                MovedTarPaths.Add(node.ChildNodes[0].Value.ToString());
                            }
                        }
                        File.Delete("XmlTarPath.xml");
                        //string SaveTotalPath = @"\\Lwp\f\开单测试";                      


                        //1 保存订单包
                        Order = SODAL.UpdateOrderBag(OrderID, OrderBagCode, orderName, orderPriority, shopID, orderTime, preCompleteTime, orderRemark, userId);

                        //照片路径: 总路径/商户/日期/订单包ID_包名/客户/产品名称
                        string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //路径到订单包
                        //2 保存产品
                        int xuhao = 1;  //订单包内照片的序号
                        foreach (ProductInfo product in ListProduct)
                        {
                            string productPath = daoBaoMing + "\\" + product.CtmName + "\\" + product.ProductName;//产品路径
                            //创建产品目录与备份目录
                            string productBackupPath = productPath + "\\" + "Backup";
                            if (!Directory.Exists(productBackupPath))
                            {
                                Directory.CreateDirectory(productBackupPath);
                                productPaths.Add(productPath);                  //产品路径
                                productPaths.Add(productBackupPath);            //备份路径
                            }
                            orderInfo newProduct = new orderInfo();
                            addProductInfo.Add(newProduct);
                            newProduct.CompleteTime = DateTime.Now;
                            newProduct.CtmName = product.CtmName;
                            newProduct.Height = product.Height;
                            newProduct.IsEdit = false;
                            newProduct.OrderPath = productPath;
                            newProduct.OrderProductCode = "2222222222";
                            newProduct.OrderProductName = product.ProductName;
                            newProduct.OrilOrderPath = product.OrilOrderPath;                       //订单内照片的原始目录



                            newProduct.Priority = orderPriority;
                            newProduct.productNum = product.ProductNum;
                            newProduct.SinglePageNum = product.SinglePageNum;
                            newProduct.MultiPageNum = product.MultiPageNum;
                            newProduct.OrderType = product.ProductPayType;//外部返单产品
                            newProduct.ProductType = product.ProductTypeCode;

                            if (!string.IsNullOrEmpty(product.StringCostItems))
                            {
                                string[] itemsArr = product.StringCostItems.Split(',');

                                List<CommonChargeItem> listItems = SODAL.GetAllCostItems();
                                newProduct.CommonChargeItem = new System.Data.Objects.DataClasses.EntityCollection<CommonChargeItem>();
                                foreach (string itemName in itemsArr)
                                {
                                    CommonChargeItem item = listItems.FirstOrDefault(p => p.ItemName == itemName.Trim());
                                    if (item != null)
                                    {
                                        newProduct.CommonChargeItem.Add(item);
                                    }
                                }
                            }

                            if (newProduct.Priority >= 7)
                                newProduct.Remark = product.ProductRemark + "\\急件";
                            else
                                newProduct.Remark = product.ProductRemark;

                            newProduct.status = (int)COM.OrderInfoStatus.WaitCheck;

                            newProduct.Tb_OrderBag = Order;
                            Tb_Product yproduct = SODAL.GetProductByProductID(product.ProductID);
                            newProduct.Tb_Product = yproduct;
                            newProduct.Width = product.Width;

                            //3 保存照片
                            //产品开单后的临时路径
                            double photoAreas = 0;//产品中照片的总面积
                            foreach (STPhoto photo in product.Photos)
                            {
                                //photoAreas = 0;
                                photoInfo newPhoto = new photoInfo();
                                addPhotoInfo.Add(newPhoto);
                                string realHW = photo.PhotoHWStandard;
                                int index = 0;
                                double realH = 0;
                                double realW = 0;
                                if (realHW != null)
                                {
                                    index = realHW.IndexOf("×");
                                    realH = Convert.ToDouble(realHW.Substring(0, index));
                                    realW = Convert.ToDouble(realHW.Substring(index + 1));
                                }
                                newPhoto.orderInfo = newProduct;

                                foreach (paperFace face in ListPaperFace)
                                {
                                    if (face.PaperFaceID == photo.PhotoFaceID)
                                    {
                                        newPhoto.paperFace = face;
                                        break;
                                    }
                                }
                                foreach (paperType type in ListPaperType)
                                {
                                    if (type.PaperTypeID == photo.PhotoTypeID)
                                    {
                                        newPhoto.paperType = type;
                                        break;
                                    }
                                }
                                newPhoto.PhotoBarCode = "3333333333";
                                string sx = string.Format("{0:d3}", xuhao); //照片在订单包中的顺序
                                //int intMark = photo.PhotoName.LastIndexOf("\\");
                                //string strPhotoPath = "";

                                //if (intMark > 0)
                                //{
                                //    strPhotoPath = photo.PhotoName.Substring(intMark + 1);
                                //}
                                //else
                                //{
                                //    strPhotoPath = photo.PhotoName;
                                //}
                                newPhoto.photoName = photo.PhotoName; //照片名字
                                newPhoto.picPath = productPath + "\\" + OrderBagCode + "_" + sx + "_" + photo.PhotoName; //照片路径
                                newPhoto.pixHeight = photo.PixHeight;
                                newPhoto.pixWidth = photo.PixWidth;

                                newPhoto.printerId = 0; //打印机?
                                newPhoto.Remark = photo.PhotoRemark;
                                newPhoto.Height = realH;
                                newPhoto.Width = realW;
                                newPhoto.TotalNum = photo.PhotoNum;
                                photoAreas += Convert.ToDouble((photo.PhotoStandardHCompute * 2.54) * (photo.PhotoStandardWCompute * 2.54) / 10000 * newPhoto.TotalNum); //累计订单中照片的总面积计算一底多张
                                newPhoto.status = (int)COM.PhotoStatus.WaitPhotoMove; //照片还未移动
                                newPhoto.IsModifySize = photo.IsModifySize;

                                //照片原路径设为产品Backup路径
                                //newPhoto.OldPicPath = productBackupPath + "\\" + newPhoto.photoName;
                                string allPath = photo.PhotoFullPath;
                                int index4 = allPath.IndexOf(shopName);
                                int length4 = shopName.Length;
                                newPhoto.OldPicPath = allPath.Substring(0, index4 + length4) + "\\已开单" +
                                                      allPath.Substring(index4 + length4);
                                photo.OldPicPath = newPhoto.OldPicPath;             //在剪切照片到"等待开单\已开单"使用
                                newPhoto.printerId = product.PrinterId;             //默认打印机

                                xuhao++;
                                /*
                                if (!Directory.Exists(photoPath))
                                {
                                    Directory.CreateDirectory(photoPath);
                                }
                                //复制照片到本地已开单目录下
                                bool isIn = false;
                                foreach (string tar in MovedTarPaths)
                                {
                                    if (tar == newPhoto.OldPicPath)
                                    {
                                        isIn = true;
                                        MovedTarPaths.Remove(tar);
                                        break;
                                    }
                                }
                                if (isIn == false) //照片还未移动才移动
                                {
                                    if (!File.Exists(newPhoto.OldPicPath))
                                    {
                                        File.SetAttributes(photo.PhotoFullPath, FileAttributes.Normal);             //去掉只读属性
                                        File.Move(photo.PhotoFullPath, newPhoto.OldPicPath);
                                    }
                                }
                                DeleteDirectory(photo.PhotoFullPath.Substring(0, photo.PhotoFullPath.LastIndexOf("\\")));
                                 * */
                                PhotoTemps.Add(newPhoto.OldPicPath);        //断网出错控制
                            }

                            //orderAreas += newProduct.Area;//统计订单的总面积 写入业绩
                            //4 WorkFlowList
                            List<STProductTech> workTechs = product.techs;
                            workTechs.Sort(CompareTechASC);         //按WorkOrder排序
                            int j = 0;
                            DateTime lastTechTime = orderTime;                //上个节点的完成时间(已开单时间初始化)
                            foreach (STProductTech tech in workTechs)
                            {
                                if (tech.IsNeed == false)                           //当前产品不需要该结点
                                    continue;
                                WorkOrderFlowList work = new WorkOrderFlowList();
                                work.tb_Tech = SODAL.GetTechByTechID(tech.TechID);
                                double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                                work.IsEdit = false;
                                if (j == 0)
                                {
                                    work.Status = (int)COM.OrderFlowListStatus.Complete;
                                    work.UserId = userId;
                                    //统计开单员业绩
                                    startOrderFlows.Add(work);      //因为流程还未插入数据库，此时执行统计功能会出错，保存开单流程，插入数据后再统计
                                }
                                else if (j == 1)
                                {
                                    work.Status = (int)COM.OrderFlowListStatus.Useable;
                                    work.UserId = tech.UserId;                      //默认操作员
                                }
                                else
                                {
                                    work.Status = (int)COM.OrderFlowListStatus.Wait;
                                    work.UserId = tech.UserId;                      //默认操作员
                                }
                                work.AssignTime = lastTechTime;
                                work.ReceiveTime = lastTechTime;
                                work.PreCompleteTime = Convert.ToDateTime(work.ReceiveTime).AddHours(techNeedTime);
                                work.CompletedTime = work.PreCompleteTime;
                                lastTechTime = Convert.ToDateTime(work.CompletedTime);
                                work.WorkOrder = tech.WorkOrder;
                                if (tech.Techtype == (int)TechType.OutProduct && tech.OutShopId != 0)    //设置了默认委外商
                                {
                                    OutProcessRecord opr = new OutProcessRecord();          //这样做可能还不能成功(因为这里产品并没有保存进数据库)
                                    opr.orderInfo = newProduct;
                                    opr.OutProcessShop = SODAL.GetOutShopByOutShopId(tech.OutShopId);
                                    opr.CreateTime = Convert.ToDateTime(work.AssignTime);
                                    opr.OutRemark = "";
                                    opr.PreFetchTime = lastTechTime;
                                    opr.FetchTime = lastTechTime;
                                    opr.FetchRemark = "";
                                    opr.users = SODAL.GetUserByUserId(userId);
                                    opr.users1 = SODAL.GetUserByUserId(userId);
                                    opr.Status = (int)COM.OutProcessRecordStatus.OutWaitFenDui;
                                    opr.Status2 = (int)COM.OutProcessRecordStatus2.Wait;
                                    opr.OperateUser = userId;
                                }
                                newProduct.WorkOrderFlowList.Add(work);
                                j++;

                            }

                            //写入开单面积
                            STProductTech Designtech = workTechs.FirstOrDefault(p => p.IsDesign && p.IsNeed);
                            int intPageNum = 0;//照片张数
                            newProduct.PageNum = product.PageNum;
                            photoAreas = photoAreas * product.ProductNum;//总面积
                            if (product.PageNum == -1)//单张片做产品比如水晶框之类
                            {
                                intPageNum = product.Photos.Count * product.ProductNum;
                            }
                            else
                            {
                                intPageNum = product.Photos.Count * product.ProductNum;
                            }
                            if (Designtech != null)
                            {
                                newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * product.PageNum * product.ProductNum);//按照设计好产品的尺寸计算

                                switch (newProduct.ProductType)
                                {
                                    case (int)OrderInfoProductType.NoNeedDesignPrint:
                                        newProduct.ProductType = (int)OrderInfoProductType.NeedDesignPrint;
                                        break;
                                    case (int)OrderInfoProductType.NoNeedDesignProduct:
                                        newProduct.ProductType = (int)OrderInfoProductType.NeedDesignProduct;
                                        break;
                                    case (int)OrderInfoProductType.NoNeedDesignKuoYin:
                                        newProduct.ProductType = (int)OrderInfoProductType.NeedDesignKuoYin;
                                        break;
                                    default:
                                        break;
                                }
                            }
                            else
                            {
                                newProduct.Area = photoAreas;//不需要设计的按照照片的实际尺寸出

                                switch (newProduct.ProductType)
                                {
                                    case (int)OrderInfoProductType.NeedDesignPrint:
                                        newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignPrint;
                                        break;
                                    case (int)OrderInfoProductType.NeedDesignProduct:
                                        newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignProduct;
                                        break;
                                    case (int)OrderInfoProductType.NeedDesignKuoYin:
                                        newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignKuoYin;
                                        break;
                                    default:
                                        break;
                                }
                                if (newProduct.ProductType == (int)OrderInfoProductType.NoNeedDesignKuoYin)//修正扩印产品的开单面积
                                {
                                    newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * intPageNum);
                                }

                            }


                        }
                        SODAL.SaveData();

                        //更新
                        foreach (orderInfo item in addProductInfo)
                        {
                            item.OrderProductCode = "2" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                        }
                        foreach (photoInfo item in addPhotoInfo)
                        {
                            item.PhotoBarCode = "3" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                        }
                        SODAL.SaveData();
                        //再对财务进行相关的审批工作
                        BillBLL.UpdateBillInfo(Order.OrderBagId, SODAL.DataEntites);
                        if (SODAL.DataEntites.Connection.State != ConnectionState.Closed)
                            SODAL.DataEntites.Connection.Close();

                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        /*
                        //删除复制的文件
                        foreach (string directory in productPaths)
                        {
                            if (Directory.Exists(directory))
                                Directory.Delete(directory, true);
                        }
                        Directory.Delete(DelPath, true);
                        
                        Tb_OrderBag order = SODAL.GetOrderBag(OrderID);
                        SODAL.DelData(order);
                        SODAL.SaveData();*/


                        foreach (photoInfo photo in addPhotoInfo)
                        {
                            SODAL.DelData(photo);
                        }
                        foreach (orderInfo product in addProductInfo)
                        {
                            SODAL.DelData(product);
                        }

                        if (SODAL.DataEntites.Connection.State != ConnectionState.Closed)
                            SODAL.DataEntites.Connection.Close();

                        //tran.Rollback();
                        throw ex;
                    }
                }
                //统计开单员业绩
                double tempArea = 0;
                foreach (WorkOrderFlowList flow in startOrderFlows)
                {
                    //workFlowListBll.StatWorkerPerfmance(flow, SODAL.DataEntites, out tempArea);
                    workFlowListBll.NewStatWorkerPerformance(flow, SODAL.DataEntites);

                }
                SODAL.SaveData();

            }
            catch (Exception ex)
            {
                //断网时，保存已经移动了的照片路径 
                DataTable DTTempTarPath = CreateTempTarPathDT();
                foreach (string s in PhotoTemps)
                {
                    DTTempTarPath.Rows.Add(s);
                }
                foreach (string s in MovedTarPaths)
                {
                    DTTempTarPath.Rows.Add(s);
                }
                if (SODAL.DataEntites.Connection.State != ConnectionState.Closed)
                    SODAL.DataEntites.Connection.Close();
                DTTempTarPath.WriteXml("XmlTarPath.xml");
                throw ex;
            }
            //开单完成后进行相关的统计工作
            workFlowListBll.StataOrderBagInfo(OrderID);
            ////再对财务进行相关的审批工作
            //try
            //{
            //    BillBLL.UpdateBillInfo(Order.OrderBagId);
            //}
            //catch (Exception ex)
            //{

            //    throw ex;
            //}

        }

        #region 当目录中没有文件与子目录时，删除
        /// <summary>
        /// 当目录中没有文件与子目录时，删除
        /// </summary>
        /// <param name="directory"></param>
        public void DeleteDirectory(string directory)
        {
            try
            {
                if (Directory.Exists(directory))
                {
                    DirectoryInfo parent = Directory.GetParent(directory);
              
                    string[] files = GetFilesPath(directory);
                    string[] directorys = Directory.GetDirectories(directory);
                    if (files.Length == 0 && directorys.Length == 0)
                    {
                        try
                        {
                            Directory.Delete(directory, true);
                        }
                        catch
                        {
                            DeleteDirectoryExtreme(directory);          //强力删除目录
                        }
                        DeleteDirectory(parent.FullName);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is System.IO.IOException)
                {
                    return;
                }
                else
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 强力删除目录
        /// </summary>
        /// <param name="directory"></param>
        private void DeleteDirectoryExtreme(string directory)
        {
            try
            {
                DirectoryInfo dinfo = new DirectoryInfo(directory);
                dinfo.Attributes = FileAttributes.Normal;
                string[] files = Directory.GetFiles(directory);
                string[] directorys = Directory.GetDirectories(directory);
                if ((files != null && files.Length > 0) || (directorys != null || directorys.Length > 0))
                {
                    foreach (string subFile in files)
                    {
                        File.SetAttributes(subFile, FileAttributes.Normal);
                        File.Delete(subFile);
                    }
                    foreach (string subDirectory in directorys)
                    {
                        DeleteDirectoryExtreme(subDirectory);
                    }
                }
                Directory.Delete(directory);
            }
            catch { }
        }
        #endregion

        /// <summary>
        /// 获取商户特有的参数
        /// </summary>
        /// <param name="shopID"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        public List<string> GetShopParas(int shopID, int productID)
        {
            try
            {
                Shop_Product_Price shop = SODAL.GetShopPara(shopID, productID);
                List<string> shopParas = new List<string>();
                if (shop != null)
                {
                    //shopParas.Add(shop.paperFace.Name);
                    //shopParas.Add(shop.paperType.Name);
                }
                return shopParas;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 递归创建目录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        private int CreateDirectory(string path, int c)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!Directory.Exists(path))
                {
                    if (c == 5)
                        return c;
                    CreateDirectory(path, c + 1);
                }
                return 100;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 插入占位用的订单包,并返回订单包号
        /// </summary>
        public void AddOrderBagTemp(out int orderID, out string bagCode, int userID)
        {
            try
            {
                Tb_OrderBag orderBag = new Tb_OrderBag();
                orderBag.BagCode = "1000000000";
                orderBag.BagName = "xxx";
                Shop TempShop = SODAL.GetShopList().First();
                orderBag.Shop = TempShop;
                orderBag.OrderTime = DateTime.Now;
                orderBag.CompleteTime = DateTime.Now;
                orderBag.FetchTime = DateTime.Now;
                orderBag.Status = 100;
                orderBag.Priority = 4;
                orderBag.EditUserID = 0;
                orderBag.Type = (int)COM.OrderBagType.normal;

                users user = SODAL.GetStartOrderUser(userID);
                orderBag.users = user;

                SODAL.SaveData();

                string bagID = orderBag.EntityKey.EntityKeyValues[0].Value.ToString();
                orderID = Convert.ToInt32(bagID);
                bagCode = "1" + string.Format("{0:d9}", orderID);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 删除占位的临时订单包
        /// <summary>
        /// 删除占位的临时订单包
        /// </summary>
        /// <param name="orderID"></param>
        public void DelOrderBagTemp(int orderID)
        {
            try
            {
                Tb_OrderBag orderBag = SODAL.GetOrderBag(orderID);
                if (orderBag == null)
                    return;
                SODAL.DelData(orderBag);
                SODAL.SaveData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 纸型结构
        /// <summary>
        /// 纸型结构
        /// </summary>
        public struct STPaperType
        {
            public int PaperTypeID;
            public string PaperTypeName;
        }
        #endregion

        #region 纸面结构
        /// <summary>
        /// 纸面结构
        /// </summary>
        public struct STPaperFace
        {
            public int PaperFaceID;
            public string PaperFaceName;
        }
        #endregion

        #region 商户结构
        /// <summary>
        /// 商户结构
        /// </summary>
        public struct STShop
        {
            public int ShopID;
            public string ShopName;
            public string ShopKeeper;
            public string Tel1;
            public string Tel2;
            public string Address;
            public decimal UnitPrice;
            public int paperFaceId;
            public int paperTypeId;
            public int Priority;            //商户的默认加急级别
        }
        #endregion
        public class ProductModel
        {
            public int Productid;
            public string ProductName;
            public double Width;
            public double Height;
            public int PageNum;

        }

        #region 产品流程结构
        /// <summary>
        /// 产品流程结构
        /// </summary>
        public class STProductTech
        {
            public int WorkFlowListId;
            public int ModelProductId;                          //产品模板的Id
            public int ProductID;                               //真实产品的Id
            public int TechID;
            public string TechName;
            public int WorkOrder;
            public bool IsNessesary;
            public bool IsNeed;                                 //该流程结点对于特定的产品是否需要
            public double NeedTime;                             //该节点工作所需的默认时间
            public int UserId;                                  //该节点的默认工作员工
            public int OutShopId;                               //当节点是委外时,选中的委外商
            public List<MODEL.CustomerManage.StartOrder.ProductOutShop> Pos;        //当节点是委外时，保存产品在委外节点的所有可用委外商
            public bool IsCompleted;                            //节点是否已完成(编辑产品使用)完成的节点，不能再编辑
            public int Status { get; set; }//状态
            public int Techtype { get; set; }//节点类型
            public bool IsDesign            //是否设计节点
            {
                set;
                get;
            }
            //public List<CommonChargeItem_info> ListCommon{get;set;};//节点附带收费项目
            public string CommonChargeItems { get; set; }
        }
        #endregion

        #region 商户产品使用次数加1
        /// <summary>
        /// 商户产品使用次数加1
        /// </summary>
        public void ProductUseTimeAdd(int productId, int shopId)
        {
            try
            {
                SODAL.ProductUseTimeAdd(productId, shopId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取某个商户的商户节点员工关系集
        /// <summary>
        /// 获取某个商户的商户节点员工关系集
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.ShopTechUser> GetShopTechUser(int shopId)
        {
            try
            {
                return SODAL.GetShopTechUser(shopId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region
        /// <summary>
        /// 获取所有员工集合
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.User> GetAllUser()
        {
            try
            {
                return SODAL.GetAllUser();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取一个产品所有的委外商
        /// <summary>
        /// 获取一个产品所有的委外商
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.ProductOutShop> GetProductOutShop(int productId)
        {
            try
            {
                return SODAL.GetProductOutShop(productId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有委外商
        /// <summary>
        /// 获取所有委外商
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.OutShop> GetAllOutShop()
        {
            try
            {
                return SODAL.GetAllOutShop();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有打印机
        /// <summary>
        /// 获取所有打印机
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.Printer> GetAllPrinter()
        {
            try
            {
                return SODAL.GetAllPrinter();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品的默认打印机
        /// <summary>
        /// 产品的默认打印机
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public int GetProductPrinter(int productId)
        {
            return SODAL.GetProductPrinter(productId);
        }
        #endregion

        /// <summary>
        /// 产品结构(默认参数)
        /// </summary>
        //public class STProduct
        //{
        //    public int ProductSerialID { get; set; }            //产品系列ID,用于唯一标识产品
        //    public int ProductID { set; get; }                  //产品ID，同种产品会重复
        //    public string ProductName { get; set; }             //产品名称
        //    public string CtmName { get; set; }                 //客户名称
        //    public float Width { get; set; }                    //产品宽
        //    public float Height { get; set; }                   //产品高
        //    public int ProductNum { get; set; }                   //产品份数
        //    public int PageNum { get; set; }                    //Page数
        //    public int ProductCategoryID { get; set; }          //产品类别ID
        //    public string ProductCategoryName { get; set; }     //产品列表名称
        //    public string ProductRemark { get; set; }            //产品备注
        //    public bool IsNeedDesign { get; set; }              //产品是否需要设计
        //    public string PaperTypeName { get; set; }           //纸型名称
        //    public string PaperFaceName { get; set; }           //纸面名称
        //    public int ProductType { get; set; }                //1真实产品 2模板 3二者都有
        //}

        #region 产品显示结构(用于显示)
        /// <summary>
        /// 产品显示结构(用于显示)
        /// </summary>
        public class STProductDisplay
        {
            public int ProductID { set; get; }                  //产品ID，同种产品会重复
            public int ProductCategoryID { get; set; }          //产品类别ID
            public string ProductCategoryName { get; set; }     //产品列表名称
            public string ProductName { get; set; }             //产品名称
            public string ProductHW { get; set; }               //产品高宽
            public double ProductH { get; set; }                //产品高
            public double ProductW { get; set; }                //产品宽
            public string ZJCode { get; set; }                  //助记码
            public int UsedTimes { get; set; }                  //使用的次数

            //public string ProductSize
            //{
            //    get { return  }
            //}
        }
        #endregion

        #region 产品对象(订单包的组成单位)
        /// <summary>
        /// 产品对象
        /// </summary>
        public class ProductInfo
        {
            public int ProductSerialID { get; set; }            //产品系列ID，用于标识产品
            public int ProductID { get; set; }                  //产品ID(可能会有重复的ID)
            public List<STPhoto> Photos { get; set; }           //产品的照片集合
            public List<STProductTech> techs { get; set; }      //产品的流程
            public string ProductBarCode { get; set; }          //产品编码
            public string ProductName { get; set; }             //产品名称

            public string CtmName { get; set; }                 //客户名称
            public int ProductNum { get; set; }                 //产品份数
            public int PageNum { get; set; }                    //Page数
            // public int PaperTypeID { get; set; }                //纸型ID
            //public int PaperFaceID { get; set; }                //纸面ID
            //public string PaperTypeName { get; set; }           //纸型名称
            //public string PaperFaceName { get; set; }           //纸面名称
            public float Height { get; set; }                   //产品高
            public float Width { get; set; }                    //产品宽
            public int ProductCategoryID { get; set; }          //产品类别ID
            public string ProductCategoryName { get; set; }     //产品列表名称

            public int ProductTypeCode { get; set; }       //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印  5 不含照片的产品
            public bool IsNeedDesign { get; set; }              //需要设计
            public string Unit { get; set; }                    //产品的单位,用于随单位的变化的显示
            public string ProductRemark { get; set; }           //产品备注
            public int PhotoNum { get; set; }                   //照片数量
            public float PhotoAllArea { get; set; }             //产品内照片总面积
            public string OrilOrderPath2 { get; set; }          //产品内照片的原始目录
            public string OrilOrderPath { get; set; }           //产品内照片的原始目录(已添加已开单)
            public int ProductType { get; set; }                //1真实产品 2模板 3二者都有 4不需要照片的产品
            public double ProductHours { get; set; }            //产品预计用时
            public string ZJCode { get; set; }                  //助记码
            public int UsedTimes { get; set; }                  //使用的次数
            public int PrinterId { get; set; }                  //打印机
            public bool IsCheckStyle { get; set; }              //当产品为设计的产品的时候检查产品的尺寸和page数
            public float Area { get; set; }                     //产品面积
            public int SinglePageNum { get; set; }              //单页数量
            public int MultiPageNum { get; set; }               //跨页数量
            public int ProductPayType { get; set; }             //是否外部返单产品
            public string SizeInch {
                get { return this.Width + "x" + this.Height; }
            }
            // public bool IsDesgin { get; set; }                  //是否是设计的产品
            public int PaperTypeID//纸型ID
            {
                get { return _PaperTypeID; }
                set
                {
                    _PaperTypeID = value;
                    if (Photos != null && Photos.Count > 0)
                        Photos.ForEach(p => p.PhotoTypeID = value);
                }
            }

            public int PaperFaceID//纸面ID
            {

                get { return _PaperFaceID; }
                set
                {
                    _PaperFaceID = value;
                    if (Photos != null && Photos.Count > 0)
                        Photos.ForEach(p => p.PhotoFaceID = value);
                }
            }
            public string PaperTypeName//纸型名称
            {
                get { return _PaperTypeName; }
                set
                {
                    _PaperTypeName = value;
                    if (Photos != null && Photos.Count > 0)
                        Photos.ForEach(p => p.PhotoTypeName = value);
                }
            }
            public string PaperFaceName
            {
                get { return _PaperFaceName; }

                set
                {
                    _PaperFaceName = value;
                    if (Photos != null && Photos.Count > 0)
                        Photos.ForEach(p => p.PhotoFaceName = value);
                }
            }
            private int _PaperTypeID;
            private int _PaperFaceID;
            private string _PaperTypeName;
            private string _PaperFaceName;
            public ProductModel ProductModel;
            //private List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> CostItems { get; set; }
            public string StringCostItems//保存用
            {
                //get
                //{
                //    string stritems = "";
                //    if (CostItems != null && CostItems.Count > 0)
                //    {
                //       // stritems += .ItemName.ToString() + ",";
                //        foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in CostItems)
                //        {
                //            stritems += ddo.ItemName + ",";
                //        }
                //        stritems = stritems.TrimEnd(',');
                //        return stritems;
                //    }
                //    else
                //    {
                //        return stritems;
                //    }


                //}

                //set
                //{
                //    string strItems = value;
                //    string[] itemsArr = strItems.Split(',');
                //    List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> list = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();
                //    CostItems = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();
                //    foreach (string strItem in itemsArr)
                //    {
                //        MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo = listAllCostItems.FirstOrDefault(p => p.ItemName == strItem);
                //        if (ddo != null)
                //        {
                //            CostItems.Add(ddo);
                //        }


                //    }

                //}
                set;
                get;
            }
            public List<ProductCommonItem> ProductCommonBing
            {
                get;
                set;
            }

        }
        #endregion

        #region 照片结构
        /// <summary>
        /// 照片的结构
        /// </summary>
        public class STPhoto
        {
            public string PhotoFullPath { get; set; }           //照片的全路径
            public string OldPicPath { get; set; }              //加上“已开单”的照片全路径
            public string PhotoName { get; set; }               //照片名称
            public string PhotoSize { get; set; }               //照片大小
            public long PhotoLength { get; set; }               //照片长度(同一个产品中取得长度最大的，用于CRC校验)
            public int PhotoDPI { get; set; }                   //照片分辨率
            public float PhotoStandardHCompute { get; set; }    //标准高,用于计算
            public float PhotoStandardWCompute { get; set; }    //标准宽,用于计算
            public string PhotoHWStandard { get; set; }         //标准高宽
            public string PhotoAreaStandard { get; set; }       //标准面积
            public string PhotoHW { get; set; }                 //高宽
            public int PixHeight { get; set; }                  //像素高
            public int PixWidth { get; set; }                   //像素宽
            public string PhotoArea { get; set; }               //面积
            public string Unit { get; set; }                    //单位(在非设计类产品单位变化时使用)
            public string PhotoRemark { get; set; }             //照片备注
            public bool Selected { get; set; }                  //照片是否被选中
            public bool IsPiPei { get; set; }                   //当产品是不需要设计的产品时，照片是否与产品尺寸匹配
            public bool IsModifySize { get; set; }              //照片是否修改了尺寸
            public int PhotoNum { get; set; }                   //照片数量
            public string CrcMark { get; set; }                 //CRC码
            public bool IsInDirectory { get; set; }             //是否在选中的目录中
            public int PhotoTypeID { get; set; }                //纸型ID
            public string PhotoTypeName { get; set; }           //纸型名
            public int PhotoFaceID { get; set; }                //纸面ID
            public string PhotoFaceName { get; set; }           //纸面名
        }
        #endregion

        #region 开单产品树
        /// <summary>
        /// 开单产品树
        /// </summary>
        public class OrderTree
        {
            public string ShopName;
            public string ShopText;
            public string ShopFullName;
            public List<OrderCtm> Ctms = new List<OrderCtm>();
        }
        public class OrderCtm
        {
            public string CtmName;
            public string CtmText;
            public string CtmFullName;
            public List<OrderProduct> Products = new List<OrderProduct>();
        }
        public class OrderProduct
        {
            public string ProductName;
            public string ProductText;
            public string ProductFullName;
            public List<ProductCC> Ccs = new List<ProductCC>();         //产品内的不同尺寸目录
        }
        public class ProductCC              //产品内的不同尺寸目录
        {
            public string CCName;
            public string CCText;
            public string CCFullName;
        }
        #endregion

        #region 按结点次序倒序
        /// <summary>
        /// 按结点次序倒序
        /// </summary>
        public static int CompareTech(STProductTech compare1, STProductTech compare2)
        {
            if (compare1.WorkOrder > compare2.WorkOrder)
                return -1;
            else
                return 1;
        }
        #endregion

        #region 按节点次序升序
        /// <summary>
        /// 按节点次序升序
        /// </summary>
        /// <returns></returns>
        public static int CompareTechASC(STProductTech para1, STProductTech para2)
        {
            if (para1.WorkOrder > para2.WorkOrder)
                return 1;
            else if (para1.WorkOrder == para2.WorkOrder)
                return 0;
            else
                return -1;
        }
        #endregion

        #region 整形数组倒序的方法
        /// <summary>
        /// 整形数组倒序的方法
        /// </summary>
        public static int CompareInt(int para1, int para2)
        {
            if (para1 > para2)
                return -1;
            else if (para1 == para2)
                return 0;
            else
                return 1;
        }
        #endregion

        //-----------------------------------------------------------
        //--------------------编辑订单包的操作-----------------------
        //-----------------------------------------------------------

        #region 获取产品的默认流程
        /// <summary>
        /// 获取产品的默认流程 
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public List<STProductTech> GetDefaultTechsOfProduct(int productID)
        {
            try
            {
                List<STProductTech> techs = new List<STProductTech>();
                List<Tb_FlowTemplate> query = SOEDAL.GetDefaultFlowsOfProduct(productID);
                foreach (Tb_FlowTemplate tech in query)
                {
                    STProductTech newTech = new STProductTech();
                    newTech.IsNessesary = tech.IsNecessery;
                    newTech.ProductID = productID;
                    newTech.TechID = tech.tb_Tech.TechId;
                    newTech.TechName = tech.tb_Tech.TechName;
                    newTech.WorkOrder = tech.WorkOrder;
                    newTech.NeedTime = Convert.ToDouble(tech.tb_Tech.NeedTime);
                    newTech.Techtype = tech.tb_Tech.TechType;
                    newTech.IsDesign = tech.tb_Tech.IsDesign;
                    string ccis = "";
                    //newTech.ListCommon=new List<CommonChargeItem_info>;
                    //加载节点附带的收费项目
                    if (!tech.tb_Tech.CommonChargeItem.IsLoaded)
                    {
                        tech.tb_Tech.CommonChargeItem.Load();
                    }
                    List<CommonChargeItem> listCCI = tech.tb_Tech.CommonChargeItem.ToList();
                    foreach (CommonChargeItem cci in listCCI)
                    {
                        ccis += cci.ItemName + ",";
                    }
                    newTech.CommonChargeItems = ccis.Trim(',');
                    techs.Add(newTech);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        public List<STProductTech> GetRealTechsOfProduct(int inOrderProductID)
        {

            try
            {
                List<STProductTech> techs = new List<STProductTech>();
                List<WorkOrderFlowList> listFlowWork = SOEDAL.GetRealFlow(inOrderProductID);
                foreach (WorkOrderFlowList flow in listFlowWork)
                {
                    if (!flow.tb_TechReference.IsLoaded)
                    {
                        flow.tb_TechReference.Load();
                    }
                    tb_Tech tech = flow.tb_Tech;

                    STProductTech newTech = new STProductTech();
                    newTech.IsNessesary = tech.IsNecessary;

                    //newTech.ProductID = productID;
                    newTech.TechID = tech.TechId;
                    newTech.TechName = tech.TechName;
                    newTech.WorkOrder = tech.WokerOrder;
                    newTech.NeedTime = Convert.ToDouble(tech.NeedTime);
                    newTech.Techtype = tech.TechType;
                    newTech.IsDesign = tech.IsDesign;
                    newTech.IsNeed = true;
                    string ccis = "";
                    //newTech.ListCommon=new List<CommonChargeItem_info>;
                    //加载节点附带的收费项目
                    if (!tech.CommonChargeItem.IsLoaded)
                    {
                        tech.CommonChargeItem.Load();
                    }
                    List<CommonChargeItem> listCCI = tech.CommonChargeItem.ToList();
                    foreach (CommonChargeItem cci in listCCI)
                    {
                        ccis += cci.ItemName + ",";
                    }
                    newTech.CommonChargeItems = ccis.Trim(',');
                    techs.Add(newTech);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #region 获取产品已分配的流程
        /// <summary>
        /// 获取产品已分配的流程
        /// </summary>
        /// <returns></returns>
        public List<STProductTech> GetProductTechs(int productID)
        {
            try
            {
                List<STProductTech> techs = new List<STProductTech>();
                List<WorkOrderFlowList> query = SOEDAL.GetProductTechs(productID);
                foreach (WorkOrderFlowList tech in query)
                {
                    STProductTech newTech = new STProductTech();
                    newTech.WorkFlowListId = tech.WorkFlowListId;
                    newTech.ProductID = productID;
                    if (!tech.orderInfo.Tb_ProductReference.IsLoaded)
                    {
                        tech.orderInfo.Tb_ProductReference.Load();
                    }
                    newTech.ModelProductId = tech.orderInfo.Tb_Product.ProuctId;
                    newTech.TechID = tech.tb_Tech.TechId;
                    newTech.TechName = tech.tb_Tech.TechName;
                    newTech.WorkOrder = tech.WorkOrder;
                    newTech.IsNeed = true;
                    newTech.UserId = tech.UserId;                   //节点已分配的员工
                    techs.Add(newTech);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private EditOrderDAL SOEDAL = new EditOrderDAL();

        #region 获取订单的头信息
        /// <summary>
        /// 获取订单的头信息
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public STOrderBagTitle GetOrderBagTitle(int orderID)
        {
            try
            {
                Tb_OrderBag query = SOEDAL.GetOrderBagTitle(orderID);
                STOrderBagTitle orderTitle = new STOrderBagTitle();
                orderTitle.PreCompleteTime = query.FetchTime;
                orderTitle.OrderBagCode = query.BagCode;
                orderTitle.OrderID = query.OrderBagId;
                orderTitle.OrderName = query.BagName;
                orderTitle.OrderPriority = query.Priority;
                orderTitle.OrderRemark = query.Remark;
                orderTitle.OrderTime = query.OrderTime;
                orderTitle.ShopName = query.Shop.shopName;
                return orderTitle;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取指定订单包的产品信息
        /// <summary>
        /// 获取指定订单包的产品信息
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public List<ProductInfoEdit> GetOrderInfoByOrderID(int orderID)
        {
            try
            {
                List<orderInfo> products = SOEDAL.GetOrderInfoByOrderID(orderID);
                List<ProductInfoEdit> productList = new List<ProductInfoEdit>();
                foreach (orderInfo product in products)
                {
                    ProductInfoEdit p = new ProductInfoEdit();
                    p.ProductSerialID = 0;                      //表示是已有的产品
                    p.OrderProductId = product.OrderProductId;
                    p.ProductID = product.Tb_Product.ProuctId;
                    p.Photos = null;                            //双击产品时才加载
                    p.techs = null;                             //双击产品时才加载
                    p.ProductBarCode = product.OrderProductCode;
                    p.ProductName = product.OrderProductName;
                    p.CtmName = product.CtmName;
                    p.ProductNum = product.productNum;
                    p.PageNum = product.PageNum;
                    List<int> ids = SOEDAL.GetPaperTypeAndPaperFaceForProduct(product.OrderProductId);
                    p.PaperTypeID = ids[0];                          //双击产品时才加载
                    p.PaperFaceID = ids[1];                          //双击产品时才加载
                    p.PaperTypeName = "";
                    p.PaperFaceName = "";
                    p.Height = (float)product.Height;
                    p.Width = (float)product.Width;
                    p.Unit = "厘米(cm)";                        //默认按厘米显示
                    p.ProductRemark = product.Remark;           //双击产品时才加载
                    p.PhotoNum = 0;                             //双击时才计算
                    p.PhotoAllArea = 0;                         //双击时才计算
                    p.OrilOrderPath = "";                       //新增产品进数据库才需要
                    p.ProductType = 3;                          //3表示未经过修改
                    p.OrderType = product.OrderType;

                    if (product.ProductType != (int)OrderInfoProductType.NoPhotoProduct)
                    {
                        p.ProductTypeCode = SOEDAL.GetProductTypeCode(p.ProductID); //产品类型码 
                    }
                    else
                    {
                        p.ProductTypeCode = (int)OrderInfoProductType.NoPhotoProduct;
                    }
                    product.CommonChargeItem.Load();
                    string itemStr = "";
                    foreach (CommonChargeItem item in product.CommonChargeItem)
                    {
                        itemStr += item.ItemName + ",";
                    }
                    itemStr = itemStr.TrimEnd(',');
                    p.StringCostItems = itemStr;
                    p.Status = product.status;
                    productList.Add(p);
                }
                return productList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取产品内的照片集合信息
        public List<STPhotoEdit> GetPhotoInOrderInfo(int orderProductID)
        {
            try
            {
                List<photoInfo> query = SOEDAL.GetPhotosInOrderInfo(orderProductID);
                List<STPhotoEdit> photoInOrderInfo = new List<STPhotoEdit>();
                foreach (photoInfo photo in query)
                {

                    STPhotoEdit newPhoto = new STPhotoEdit();
                    newPhoto.PhotoFullPath = photo.picPath;
                    newPhoto.PhotoNum = (int)photo.TotalNum;
                    newPhoto.PhotoID = photo.photoId;
                    newPhoto.PhotoRemark = photo.Remark;
                    photoInOrderInfo.Add(newPhoto);
                }
                return photoInOrderInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品内的照片集合信息
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <param name="type" >1表示普通编辑 2表示自动开单的编辑</param>
        /// <returns></returns>
        public List<STPhotoEdit> GetPhotoInOrderInfo(int orderProductID, int type)
        {
            try
            {
                List<photoInfo> query = SOEDAL.GetPhotosInOrderInfo(orderProductID);
                List<STPhotoEdit> photoInOrderInfo = new List<STPhotoEdit>();
                if (type == 1)                  //普通订单的编辑 ，照片路径在“已开单”里
                {
                    foreach (photoInfo photo in query)
                    {

                        STPhotoEdit newPhoto = new STPhotoEdit();
                        newPhoto.PhotoFullPath = photo.picPath;
                        newPhoto.PhotoNum = (int)photo.TotalNum;
                        newPhoto.PhotoID = photo.photoId;
                        newPhoto.PhotoRemark = photo.Remark;
                        photo.paperFaceReference.Load();
                        photo.paperTypeReference.Load();
                        newPhoto.PaperFaceID = photo.paperFace.PaperFaceID;
                        newPhoto.PaperFaceName = photo.paperFace.Name;
                        newPhoto.PaperTypeID = photo.paperType.PaperTypeID;
                        newPhoto.PaperTypeName = photo.paperType.Name;
                        photoInOrderInfo.Add(newPhoto);
                    }
                }
                else if (type == 2)             //自动开单的编辑，照片路径在“等待开单”里
                {
                    foreach (photoInfo photo in query)
                    {

                        STPhotoEdit newPhoto = new STPhotoEdit();
                        newPhoto.PhotoFullPath = photo.OldPicPath;
                        newPhoto.PhotoNum = (int)photo.TotalNum;
                        newPhoto.PhotoID = photo.photoId;
                        newPhoto.PhotoRemark = photo.Remark;
                        photo.paperFaceReference.Load();
                        photo.paperTypeReference.Load();
                        newPhoto.PaperFaceID = photo.paperFace.PaperFaceID;
                        newPhoto.PaperFaceName = photo.paperFace.Name;
                        newPhoto.PaperTypeID = photo.paperType.PaperTypeID;
                        newPhoto.PaperTypeName = photo.paperType.Name;
                        photoInOrderInfo.Add(newPhoto);
                    }
                }
                return photoInOrderInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品内的照片集合信息(自动开单产品的照片路径在等待开单中)
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <returns></returns>
        public List<STPhotoEdit> GetPhotoInOrderInfoAuto(int orderProductID)
        {
            try
            {
                List<photoInfo> query = SOEDAL.GetPhotosInOrderInfo(orderProductID);
                List<STPhotoEdit> photoInOrderInfo = new List<STPhotoEdit>();
                foreach (photoInfo photo in query)
                {

                    STPhotoEdit newPhoto = new STPhotoEdit();
                    newPhoto.PhotoFullPath = photo.OldPicPath;
                    newPhoto.PhotoNum = (int)photo.TotalNum;
                    newPhoto.PhotoID = photo.photoId;
                    newPhoto.PhotoRemark = photo.Remark;
                    photo.paperFaceReference.Load();
                    photo.paperTypeReference.Load();
                    newPhoto.PaperFaceID = photo.paperFace.PaperFaceID;
                    newPhoto.PaperFaceName = photo.paperFace.Name;
                    newPhoto.PaperTypeID = photo.paperType.PaperTypeID;
                    newPhoto.PaperTypeName = photo.paperType.Name;
                    photoInOrderInfo.Add(newPhoto);
                }
                return photoInOrderInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取产品内的照片集合信息详情
        public List<STPhotoEdit> GetPhotoInOrderInfoXQ(int orderProdictId)
        {
            try
            {
                List<photoInfo> query = SOEDAL.GetPhotosInOrderInfoXQ(orderProdictId);
                List<STPhotoEdit> photos = new List<STPhotoEdit>();
                foreach (photoInfo photo in query)
                {
                    STPhotoEdit newPhoto = new STPhotoEdit();
                    newPhoto.PhotoFullPath = photo.picPath;
                    newPhoto.PhotoID = photo.photoId;
                    newPhoto.PhotoRemark = photo.Remark;
                    float realHeight = (float)photo.Height;
                    float realWidth = (float)photo.Width;
                    newPhoto.PhotoStandardHCompute = realHeight;
                    newPhoto.PhotoStandardWCompute = realWidth;
                    photo.paperFaceReference.Load();
                    photo.paperTypeReference.Load();
                    newPhoto.PaperFaceID = photo.paperFace.PaperFaceID;
                    newPhoto.PaperFaceName = photo.paperFace.Name;
                    newPhoto.PaperTypeID = photo.paperType.PaperTypeID;
                    newPhoto.PaperTypeName = photo.paperType.Name;

                    photos.Add(newPhoto);
                }
                return photos;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取产品已分配的委外商Id
        /// <summary>
        /// 获取产品已分配的委外商Id
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOutShopIdByOrderProductId(int orderProductId)
        {
            try
            {
                return SODAL.GetOutShopIdByOrderProductId(orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 取得实际产品对应的打印机
        /// <summary>
        /// 取得产品对应的打印机
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOrderProductPrinter(int orderProductId)
        {
            try
            {
                return SODAL.GetOrderProductPrinter(orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region
        /// <summary>
        /// 获取系统时间
        /// </summary>
        /// <returns></returns>
        public DateTime GetServerTime()
        {
            try
            {
                return SODAL.GetServerTime();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 修改订单包
        /// <summary>
        /// 修改订单包
        /// </summary>
        /// <param name="products"></param>
        public void UpdateOrderBag(int orderBagID, List<ProductInfoEdit> products, List<int> DelProductIDs, List<int> DelPhotoIDs, string OrderBagCode, int OrderID, string orderName, int orderPriority, int shopID, string shopName, DateTime orderTime, DateTime preCompleteTime, string orderRemark, int editUserId)
        {
            List<WorkOrderFlowList> startOrderFlows = new List<WorkOrderFlowList>();             //新增产品的开单流程，用于统计开单员业绩
           
            DateTime serverTime = GetServerTime();                      //服务器时间

            List<string> PhotoTemps = new List<string>();               //开单断网后照片复位
            List<string> MovedTarPaths = new List<string>();            //上次断网时已移动了的照片路径
            List<orderInfo> addProductInfo = new List<orderInfo>();     //新插入的产品集合
            List<photoInfo> addPhotoInfo = new List<photoInfo>();       //新插入的照片集合
            bool isNeedMoveThisBag = false;//是否需要移动历史数据

            try
            {
                int connectTime = 0;
                System.Transactions.TransactionOptions options = new TransactionOptions();
                options.Timeout = new TimeSpan(0, 0, 600);
                options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                //using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                //{
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    try
                    {
                        //if (SOEDAL.DataEntites.Connection.State != ConnectionState.Open)
                        //{
                        //    SOEDAL.DataEntites.Connection.Open();
                        //}
                        if (db.Connection.State != System.Data.ConnectionState.Open)
                        {
                            db.Connection.Open();
                        }
                    }
                    catch (Exception ex)
                    {
                        connectTime++;
                        if (connectTime == 1)
                        {
                            UpdateOrderBag(orderBagID, products, DelProductIDs, DelPhotoIDs, OrderBagCode, OrderID, orderName, orderPriority, shopID, shopName, orderTime, preCompleteTime, orderRemark, editUserId);
                        }
                        else
                        {
                            throw ex;
                        }
                    }

                    using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                    {
                        users editUser = db.users.FirstOrDefault(u=>u.userID ==editUserId);
                        
                        List<string> AddProductPaths = new List<string>();          //新增产品的目录路径
                        try
                        {

                            //读上次断网时已移动到“已开单”下的照片路径
                            XmlDocument doc = new XmlDocument();
                            if (File.Exists("XmlTarPathEdit.xml"))
                            {
                                doc.Load("XmlTarPathEdit.xml");
                                XmlNodeList nodeList = doc.GetElementsByTagName("TarPath");
                                foreach (XmlNode node in nodeList)
                                {
                                    MovedTarPaths.Add(node.ChildNodes[0].Value.ToString());
                                }
                            }
                            File.Delete("XmlTarPathEdit.xml");
                            List<paperFace> ListPaperFace = null;
                            List<paperType> ListPaperType = null;
                            ListPaperFace = db.paperFace.ToList();       //所有纸型
                            ListPaperType = db.paperType.ToList();       //所有纸面

                            DAL.Shop currentShop =db.Shop.First(s=>s.ShopId==shopID);

                            //string SaveTotalPath = @"\\Lwp\f\开单测试";                      //照片在服务器上的总路径(需要修改)
                            string SaveTotalPath = GetOrderStorePathEdit();                 //照片在服务器上的总路径
                            //照片路径: 总路径/商户/日期/订单包ID_包名/客户/产品名称
                            //string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //路径到订单包
                            string pName;
                            photoInfo maxCodePhoto = db.photoInfo.Where(p => p.orderInfo.Tb_OrderBag.OrderBagId == orderBagID).OrderByDescending(p => p.photoName).FirstOrDefault();
                            if (maxCodePhoto == null)
                            {
                                pName ="";//无照片的产品
                            }
                            else
                            {
                                pName = maxCodePhoto.photoName;
                            }
                            //string pName = SOEDAL.GetMaxXuHaoInOrder(orderBagID);
                            int maxXuHao = 0;
                            if (string.IsNullOrEmpty(pName))
                            {
                                maxXuHao = 0;
                            }
                            else
                            {


                                int xindex = pName.IndexOf("_");
                                string cXuHao = pName.Substring(xindex + 1, 3);



                                try
                                {
                                    maxXuHao = Convert.ToInt32(cXuHao) + 1;
                                }
                                catch (Exception)
                                {

                                    maxXuHao = 0;
                                }
                            }
                            Tb_OrderBag orderBag =db.Tb_OrderBag.First(t=>t.OrderBagId==orderBagID);
                            orderBag.BagName = orderName;
                            orderBag.FetchTime = preCompleteTime;
                            orderBag.FetchTime = preCompleteTime;                           //取件
                            orderBag.EditUserID = 0;
                            orderBag.OrderTime = orderTime;
                            orderBag.Priority = orderPriority;
                            orderBag.Remark = orderRemark;
                            orderBag.Shop = currentShop;
                            orderBag.EditUserID = editUserId;
                            //修改产品加急级别
                            orderBag.orderInfo.Load();
                            foreach (orderInfo info in orderBag.orderInfo)
                            {
                                info.Priority = orderPriority;
                            }
                            //orderBag.Status = (int)COM.OrderBagStatus.Doing;                  //订单包状态
                            //orderBag.Type = (int)COM.OrderBagType.normal;                    //type=?
                            //订单路径
                            //string oneProductPath = SOEDAL.GetAOrderInfoPathInOrder(OrderID);
                            string oneProductPath = db.orderInfo.Where(p => p.Tb_OrderBag.OrderBagId == OrderID).FirstOrDefault().OrderPath;
                            string part = oneProductPath.Substring(0, oneProductPath.LastIndexOf("\\"));    //到客户
                            string orderPath = part.Substring(0, part.LastIndexOf("\\"));              //订单的原路径
                            //流程状态
                            //int flowWait = (int)COM.OrderFlowListStatus.Wait;
                            //int flowDoing = (int)COM.OrderFlowListStatus.Useable;
                            //int flowCompleted = (int)COM.OrderFlowListStatus.Complete;

                            foreach (ProductInfoEdit product in products)
                            {
                                Tb_Product yproduct = db.Tb_Product.First(p=>p.ProuctId==product.ProductID);
                                //1 新增产品
                                if (product.ProductType == 1)
                                {
                                    #region 新增产品
                                    //string productPath = daoBaoMing + "\\" + product.CtmName + "\\" + product.ProductName;//产品路径
                                    string productPath = orderPath + "\\" + product.CtmName + "\\" + product.ProductName;//产品路径
                                    //创建产品目录与备份目录
                                    string productBackupPath = productPath + "\\" + "Backup";
                                    if (!Directory.Exists(productPath))
                                    {
                                        Directory.CreateDirectory(productBackupPath);   //创建备份目录的同时会创建产品目录
                                        AddProductPaths.Add(productPath);                  //产品路径
                                        AddProductPaths.Add(productBackupPath);            //备份路径
                                    }
                                    //产品
                                    orderInfo newProduct = new orderInfo();

                                    addProductInfo.Add(newProduct);
                                    newProduct.CompleteTime = DateTime.Now;
                                    newProduct.CtmName = product.CtmName;
                                    newProduct.Height = product.Height;
                                    newProduct.IsEdit = false;
                                    newProduct.OrderPath = productPath;
                                    newProduct.OrderProductCode = "2222222222";
                                    newProduct.OrderProductName = product.ProductName;
                                    newProduct.OrilOrderPath = product.OrilOrderPath;
                                    newProduct.PageNum = product.PageNum;
                                    newProduct.productNum = product.ProductNum;
                                    newProduct.Priority = orderPriority;
                                    if (newProduct.Priority >= 7)
                                    {
                                        if (!product.ProductRemark.EndsWith("急件"))
                                            newProduct.Remark = product.ProductRemark + "\\急件";
                                    }
                                    else
                                    {
                                        newProduct.Remark = product.ProductRemark;
                                    }
                                    //if (product.ProductType == 4)//不需要照片的产品
                                    //{
                                        newProduct.status = (int)COM.OrderInfoStatus.Doing;      //产品状态为"等待移动照片"

                                    //}
                                    //else
                                    //{
                                    //    newProduct.status = (int)COM.OrderInfoStatus.WaitPhotoMove;      //产品状态为"等待移动照片"
                                    //}
                                    newProduct.Tb_OrderBag = orderBag;
                                    newProduct.Tb_Product = yproduct;
                                    newProduct.Width = product.Width;

                                    double photoAreas = 0;
                                    foreach (STPhotoEdit photo in product.Photos)
                                    {
                                        //照片
                                        photoInfo newPhoto = new photoInfo();
                                        addPhotoInfo.Add(newPhoto);
                                        string realHW = photo.PhotoHWStandard;
                                        int index = 0;
                                        double realH = 0;
                                        double realW = 0;
                                        if (realHW != null)
                                        {
                                            index = realHW.IndexOf("×");
                                            realH = Convert.ToDouble(realHW.Substring(0, index));
                                            realW = Convert.ToDouble(realHW.Substring(index + 1));
                                        }
                                        newPhoto.Height = realH;
                                        newPhoto.orderInfo = newProduct;
                                        foreach (paperFace face in ListPaperFace)
                                        {
                                            if (face.PaperFaceID == photo.PaperFaceID)
                                            {
                                                newPhoto.paperFace = face;
                                                break;
                                            }
                                        }
                                        foreach (paperType type in ListPaperType)
                                        {
                                            if (type.PaperTypeID == photo.PaperTypeID)
                                            {
                                                newPhoto.paperType = type;
                                                break;
                                            }
                                        }
                                        newPhoto.PhotoBarCode = "3333333333";
                                        string sx = string.Format("{0:d3}", maxXuHao);              //照片在订单包中的顺序
                                        newPhoto.photoName = OrderBagCode + "_" + sx + "_" + photo.PhotoName;                //照片名字
                                        newPhoto.picPath = productPath + "\\" + newPhoto.photoName;                                //照片路径
                                        newPhoto.pixHeight = photo.PixHeight;
                                        newPhoto.pixWidth = photo.PixWidth;
                                        //newPhoto.printerId = 0;                                 //打印机?
                                        newPhoto.printerId = product.PrinterId;                     //默认的打印机
                                        newPhoto.Remark = photo.PhotoRemark;
                                        newPhoto.Width = realW;
                                        newPhoto.status = (int)COM.PhotoStatus.WaitPhotoMove;       //照片等待移动
                                        newPhoto.IsModifySize = photo.IsModifySize;
                                        newPhoto.TotalNum = photo.PhotoNum;
                                        //照片原路径设为Backup路径
                                        string allPath = photo.PhotoFullPath;
                                        int index4 = allPath.IndexOf(shopName);
                                        int length4 = shopName.Length;
                                        newPhoto.OldPicPath = allPath.Substring(0, index4 + length4) + "\\已开单" + allPath.Substring(index4 + length4);
                                        string photoPath = newPhoto.OldPicPath.Substring(0, newPhoto.OldPicPath.LastIndexOf("\\"));
                                        maxXuHao++;
                                        photoAreas += Convert.ToDouble((newPhoto.Width * 2.54) * (newPhoto.Height * 2.54) / 10000 * newPhoto.TotalNum);//累计照片中的实际面积
                                        if (!Directory.Exists(photoPath))
                                        {
                                            Directory.CreateDirectory(photoPath);
                                        }
                                        //复制照片到本地已开单目录下
                                        bool isIn = false;
                                        foreach (string tar in MovedTarPaths)
                                        {
                                            if (tar == newPhoto.OldPicPath)
                                            {
                                                isIn = true;
                                                MovedTarPaths.Remove(tar);
                                                break;
                                            }
                                        }
                                        if (isIn == false)       //照片还未移动才移动
                                        {
                                            if (!File.Exists(newPhoto.OldPicPath))
                                            {
                                                File.SetAttributes(photo.PhotoFullPath, FileAttributes.Normal);         //去掉只读属性
                                                File.Move(photo.PhotoFullPath, newPhoto.OldPicPath);
                                            }
                                        }
                                        DeleteDirectory(photo.PhotoFullPath.Substring(0, photo.PhotoFullPath.LastIndexOf("\\")));
                                        PhotoTemps.Add(newPhoto.OldPicPath);            //断网使用
                                    }


                                    //4 WorkFlowList
                                    List<STProductTech> workTechs = product.techs;
                                    workTechs.Sort(CompareTechASC);         //按WorkOrder排序
                                    int j = 0;
                                    DateTime lastTechTime = serverTime;     //新增产品的节点时间以服务器时间为基础
                                    foreach (STProductTech tech in workTechs)
                                    {
                                        if (tech.IsNeed == false)                           //当前产品不需要该结点
                                            continue;
                                        WorkOrderFlowList work = new WorkOrderFlowList();
                                        work.tb_Tech = db.tb_Tech.First(t=>t.TechId==tech.TechID);
                                        double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                                        work.IsEdit = false;
                                        if (j == 0)
                                        {
                                            work.Status = (int)COM.OrderFlowListStatus.Complete;
                                            work.UserId = editUserId;
                                            //计算开单员业绩
                                            startOrderFlows.Add(work);
                                        }
                                        else if (j == 1)
                                        {
                                            work.Status = (int)COM.OrderFlowListStatus.Useable;
                                            work.UserId = tech.UserId;                  //节点默认操作员
                                        }
                                        else
                                        {
                                            work.Status = (int)COM.OrderFlowListStatus.Wait;
                                            work.UserId = tech.UserId;                  //节点默认操作员
                                        }
                                        work.AssignTime = lastTechTime;
                                        work.ReceiveTime = lastTechTime;
                                        work.PreCompleteTime = Convert.ToDateTime(work.ReceiveTime).AddHours(techNeedTime);
                                        work.CompletedTime = work.PreCompleteTime;
                                        lastTechTime = Convert.ToDateTime(work.CompletedTime);
                                        work.WorkOrder = tech.WorkOrder;
                                        if (tech.Techtype == (int)TechType.OutProduct && tech.OutShopId != 0)    //设置了默认委外商
                                        {
                                            OutProcessRecord opr = new OutProcessRecord();          //这样做可能还不能成功(因为这里产品并没有保存进数据库)
                                            opr.orderInfo = newProduct;
                                            opr.OutProcessShop =db.OutProcessShop.First(o=>o.OutShopId==tech.OutShopId);
                                            opr.CreateTime = Convert.ToDateTime(work.AssignTime);
                                            opr.OutRemark = "";
                                            opr.PreFetchTime = lastTechTime;
                                            opr.FetchTime = lastTechTime;
                                            opr.FetchRemark = "";
                                            //opr.users = SODAL.GetUserByUserId(editUserId);
                                            //opr.users1 = SODAL.GetUserByUserId(editUserId);
                                            opr.users =db.users.FirstOrDefault(u=>u.userID==editUserId);
                                            opr.users1 = opr.users;
                                            opr.Status = (int)COM.OutProcessRecordStatus.OutWaitFenDui;
                                            opr.Status2 = (int)COM.OutProcessRecordStatus2.Wait;
                                            opr.OperateUser = editUserId;
                                        }
                                        newProduct.WorkOrderFlowList.Add(work);
                                        j++;
                                    }
                                    STProductTech designTech = workTechs.FirstOrDefault(p => p.IsDesign && p.IsNeed);
                                    int intPageNum = 0;
                                    //newProduct.PageNum = product.PageNum;
                                    if (newProduct.PageNum == -1)//单张片做产品比如水晶框之类
                                    {
                                        intPageNum = newProduct.photoInfo.Count;
                                    }
                                    else
                                    {
                                        intPageNum = newProduct.PageNum;
                                    }
                                    if (designTech != null)//设计类的要按产品的算
                                    {
                                        newProduct.Area = (newProduct.Height * 2.54) * (newProduct.Width * 2.54) / 10000 * intPageNum;

                                        switch (newProduct.ProductType)
                                        {
                                            case (int)OrderInfoProductType.NoNeedDesignPrint:
                                                newProduct.ProductType = (int)OrderInfoProductType.NeedDesignPrint;
                                                break;
                                            case (int)OrderInfoProductType.NoNeedDesignProduct:
                                                newProduct.ProductType = (int)OrderInfoProductType.NeedDesignProduct;
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    else
                                    {
                                        newProduct.Area = photoAreas;

                                        switch (newProduct.ProductType)
                                        {
                                            case (int)OrderInfoProductType.NeedDesignPrint:
                                                newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignPrint;
                                                break;
                                            case (int)OrderInfoProductType.NeedDesignProduct:
                                                newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignProduct;
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    //新增产品比较特殊 业绩与开单面积在保存后添加
                                    #endregion
                                }
                                //2 修改产品
                                else if (product.ProductType == 2)
                                {
                                    #region 修改产品
                                    double photoAreas = 0;
                                    List<photoInfo> ListPhoto = db.photoInfo.Where(p=>p.orderInfo.OrderProductId==product.OrderProductId).ToList();
                                    orderInfo modifyProduct = db.orderInfo.First(o=>o.OrderProductId==product.OrderProductId);
                                    if (!modifyProduct.WorkOrderFlowList.IsLoaded)
                                        modifyProduct.WorkOrderFlowList.Load();
                                    foreach (var item in  modifyProduct.WorkOrderFlowList)
                                    {
                                        if (!item.tb_TechReference.IsLoaded)
                                            item.tb_TechReference.Load();
                                    }
                                    photoInfo modelPhoto = ListPhoto.FirstOrDefault();              //产品内已有的照片
      
                                    string productPath = "";
                                    if (modelPhoto == null)
                                    {
                                        productPath = modifyProduct.OrderPath;
                                    }
                                    else
                                    {
                                        productPath = modelPhoto.picPath.Substring(0, modelPhoto.picPath.LastIndexOf("\\"));

                                    }
                                    // string productPath = modifyProduct.OrderPath;
                                    //创建产品目录与备份目录
                                    modifyProduct.OrderProductName = product.ProductName;
                                    modifyProduct.CompleteTime = DateTime.Now;
                                    modifyProduct.CtmName = product.CtmName;
                                    modifyProduct.Height = product.Height;
                                    modifyProduct.IsEdit = false;
                                    modifyProduct.OrderProductName = product.ProductName;
                                    //modifyProduct.OrilOrderPath = product.OrilOrderPath;
                                    modifyProduct.PageNum = product.PageNum;
                                    modifyProduct.productNum = product.ProductNum;
                                    //modifyProduct.Priority = orderPriority;
                                    if (modifyProduct.Priority >= 7)
                                    {
                                        if (!product.ProductRemark.EndsWith("急件"))
                                        {
                                            modifyProduct.Remark = product.ProductRemark + "\\急件";
                                        }
                                    }
                                    //modifyProduct.Remark = product.ProductRemark;
                                    //modifyProduct.Remark = editUser == null ? "" : editUser.UserName + " 修改时间：" + DateTime.Now + " " + modifyProduct.Remark;
                                    modifyProduct.Remark = product.ProductRemark+"\\"+(editUser == null ? "" : editUser.UserName) + " 修改时间：" + DateTime.Now + " ";
                                    //modifyProduct.status = (int)COM.OrderInfoStatus.Doing;                                                  //需要修改
                                    modifyProduct.Tb_OrderBag = orderBag;
                                    modifyProduct.Tb_Product = yproduct;
                                    modifyProduct.Width = product.Width;
                                    //只要是修改的产品，其内部所有的照片都要执行 1纸型、纸面 2员工 3打印机 4委外商    的修改操作
                                    paperFace selectedFace = null;
                                    foreach (paperFace face in ListPaperFace)
                                    {
                                        if (face.PaperFaceID == product.PaperFaceID)
                                        {
                                            selectedFace = face;
                                            break;
                                        }
                                    }
                                    paperType selectedType = null;
                                    foreach (paperType type in ListPaperType)
                                    {
                                        if (type.PaperTypeID == product.PaperTypeID)
                                        {
                                            selectedType = type;
                                            break;
                                        }
                                    }
                                    //修改附加收费类型

                                    // modifyProduct.CommonChargeItem.Clear();
                                    modifyProduct.CommonChargeItem.Load();

                                    List<CommonChargeItem> listOld = modifyProduct.CommonChargeItem.ToList();

                                    foreach (CommonChargeItem item in listOld)
                                    {
                                        //SOEDAL.Delete(item);
                                        modifyProduct.CommonChargeItem.Remove(item);
                                    }
                                    //if (listOld.Count == 0)
                                    //{
                                    //    modifyProduct.CommonChargeItem = new System.Data.Objects.DataClasses.EntityCollection<CommonChargeItem>();

                                    //}
                                    List<CommonChargeItem> AllItems = db.CommonChargeItem.ToList();

                                    string[] itemsArr = product.StringCostItems.Split(',');
                                    foreach (string itemName in itemsArr)
                                    {
                                        if (!string.IsNullOrEmpty(itemName))
                                        {
                                            CommonChargeItem item = AllItems.FirstOrDefault(p => p.ItemName == itemName.Trim());
                                            if (item != null)
                                            {
                                                modifyProduct.CommonChargeItem.Add(item);
                                            }
                                        }
                                    }

                                    //修改原来照片的 纸型、纸面，打印机
                                    foreach (photoInfo p in ListPhoto)          //原来的照片
                                    {
                                        p.paperFace = selectedFace;
                                        p.paperType = selectedType;
                                        p.printerId = product.PrinterId;        //默认的打印机
                                        photoAreas += Convert.ToDouble(p.Height * p.Width * 2.54 * 2.54 / 10000 * p.TotalNum);//旧照片的面积
                                    }
                                    if (modelPhoto != null)
                                    {
                                        modelPhoto.printerId = product.PrinterId;
                                    }
                                    foreach (STPhotoEdit photo in product.Photos)
                                    {
                                        int modelPrinterId = Convert.ToInt32(modelPhoto.printerId);         //新增照片的打印机，状态与已有的照片相同
                                        int modelStatus = modelPhoto.status;
                                        if (photo.PhotoType == 1)               //新增
                                        {
                                            photoInfo newPhoto = new photoInfo();
                                            addPhotoInfo.Add(newPhoto);
                                            string realHW = photo.PhotoHWStandard;
                                            int index = 0;
                                            double realH = 0;
                                            double realW = 0;
                                            if (realHW != null)
                                            {
                                                index = realHW.IndexOf("×");
                                                realH = Convert.ToDouble(realHW.Substring(0, index));
                                                realW = Convert.ToDouble(realHW.Substring(index + 1));
                                            }
                                            newPhoto.Height = realH;
                                            newPhoto.orderInfo = modifyProduct;
                                            foreach (paperFace face in ListPaperFace)
                                            {
                                                if (face.PaperFaceID == product.PaperFaceID)
                                                {
                                                    newPhoto.paperFace = face;
                                                    break;
                                                }
                                            }
                                            foreach (paperType type in ListPaperType)
                                            {
                                                if (type.PaperTypeID == product.PaperTypeID)
                                                {
                                                    newPhoto.paperType = type;
                                                    break;
                                                }
                                            }
                                            newPhoto.PhotoBarCode = "3333333333";
                                            string sx = string.Format("{0:d3}", maxXuHao);                          //照片在订单包中的顺序
                                            newPhoto.photoName = OrderBagCode + "_" + sx + "_" + photo.PhotoName;   //照片名字
                                            newPhoto.pixHeight = photo.PixHeight;
                                            newPhoto.pixWidth = photo.PixWidth;
                                            newPhoto.printerId = modelPrinterId;                                                 //打印机?
                                            newPhoto.Remark = photo.PhotoRemark;
                                            newPhoto.Width = realW;
                                            newPhoto.status = modelStatus;
                                            newPhoto.IsModifySize = photo.IsModifySize;
                                            newPhoto.TotalNum = photo.PhotoNum;
                                            newPhoto.picPath = productPath + "\\" + newPhoto.photoName;
                                            newPhoto.OldPicPath = "";
                                            photoAreas += Convert.ToDouble(newPhoto.Height * newPhoto.Width * 2.54 * 2.54 / 10000 * newPhoto.TotalNum);//新照片的面积

                                            maxXuHao++;
                                            if (!Directory.Exists(productPath))
                                            {
                                                Directory.CreateDirectory(productPath);
                                            }
                                            //复制照片到本地已开单目录下
                                            bool isIn = false;
                                            foreach (string tar in MovedTarPaths)
                                            {
                                                if (tar == newPhoto.OldPicPath)
                                                {
                                                    isIn = true;
                                                    MovedTarPaths.Remove(tar);
                                                    break;
                                                }
                                            }
                                            if (isIn == false)       //照片还未移动才移动
                                            {
                                                if (!File.Exists(newPhoto.picPath))
                                                {
                                                    File.SetAttributes(photo.PhotoFullPath, FileAttributes.Normal);         //去掉只读属性
                                                    //File.Move(photo.PhotoFullPath, newPhoto.picPath);
                                                    File.Copy(photo.PhotoFullPath, newPhoto.picPath);
                                                }
                                            }
                                            //DeleteDirectory(photo.PhotoFullPath.Substring(0, photo.PhotoFullPath.LastIndexOf("\\")));
                                            PhotoTemps.Add(newPhoto.OldPicPath);        //断网使用
                                        }
                                        else if (photo.PhotoType == 2)                  //修改
                                        {
                                            photoInfo modifyPhoto = db.photoInfo.First(p=>p.photoId==photo.PhotoID);
                                            string realHW = photo.PhotoHWStandard;
                                            int index = 0;
                                            double realH = 0;
                                            double realW = 0;
                                            if (realHW != null)
                                            {
                                                index = realHW.IndexOf("×");
                                                realH = Convert.ToDouble(realHW.Substring(0, index));
                                                realW = Convert.ToDouble(realHW.Substring(index + 1));
                                            }
                                            foreach (paperFace face in ListPaperFace)
                                            {
                                                if (face.PaperFaceID == photo.PaperFaceID)
                                                {
                                                    modifyPhoto.paperFace = face;
                                                    break;
                                                }
                                            }
                                            foreach (paperType type in ListPaperType)
                                            {
                                                if (type.PaperTypeID == photo.PaperTypeID)
                                                {
                                                    modifyPhoto.paperType = type;
                                                    break;
                                                }
                                            }
                                            modifyPhoto.Height = realH;
                                            modifyPhoto.Width = realW;
                                            modifyPhoto.pixHeight = photo.PixHeight;
                                            modifyPhoto.pixWidth = photo.PixWidth;

                                            modifyPhoto.Remark = photo.PhotoRemark;
                                            modifyPhoto.TotalNum = Convert.ToInt16(photo.PhotoNum);
                                            photoAreas += Convert.ToDouble(modifyPhoto.Height * modifyPhoto.Width * 2.54 * 2.54 / 10000 * modifyPhoto.TotalNum);//修改后照片的面积

                                        }

                                    }

                                    //修改流程
                                    #region old

                                    //List<STProductTech> oldTechs = GetProductTechs(product.OrderProductId).OrderBy(p => p.TechID).ToList();   //原有的流程
                                    ////删除不再需要的流程节点
                                    //for (int i = 0; i < oldTechs.Count; i++)
                                    //{
                                    //    bool isIn = false;
                                    //    foreach (STProductTech tech in product.techs)
                                    //    {
                                    //        if (tech.TechID == oldTechs[i].TechID)
                                    //        {
                                    //            isIn = true;
                                    //            break;
                                    //        }
                                    //    }
                                    //    if (isIn == false)
                                    //    {
                                    //        WorkOrderFlowList flow = SOEDAL.GetFlow(oldTechs[i].WorkFlowListId);
                                    //        SOEDAL.Delete(flow);
                                    //    }
                                    //}

                                    //product.techs = product.techs.OrderBy(p => p.WorkOrder).ToList();                 //按工作次序排序
                                    //STProductTech doingTech = null;//当前工作节点
                                    //bool IsSetDoingStatus = false;                                                      //是否已设置当前流程节点
                                    //if (product.DoingTechId != 0)
                                    //    doingTech = product.techs.Find(p => p.TechID > product.DoingTechId);

                                    //foreach (STProductTech tech in product.techs)
                                    //{
                                    //    bool isIn = false;
                                    //    for (int i = 0; i < oldTechs.Count; i++)
                                    //    {
                                    //        if (tech.WorkOrder == oldTechs[i].WorkOrder && tech.IsNeed == true)
                                    //        {
                                    //            isIn = true;
                                    //            WorkOrderFlowList flow = SOEDAL.GetFlow(oldTechs[i].WorkFlowListId);        //原来的流程全部都修改操作员
                                    //            flow.UserId = tech.UserId;
                                    //            break;
                                    //        }
                                    //        else if (tech.WorkOrder == oldTechs[i].WorkOrder && tech.IsNeed == false)       //删除
                                    //        {
                                    //            isIn = true;
                                    //            WorkOrderFlowList flow = SOEDAL.GetFlow(oldTechs[i].WorkFlowListId);
                                    //            if ((flow.Status == (int)COM.OrderInfoStatus.Doing || flow.Status == (int)COM.OrderInfoStatus.Stop) && i < oldTechs.Count - 1)
                                    //            {
                                    //                WorkOrderFlowList nextFlow = SOEDAL.GetFlow(oldTechs[i + 1].WorkFlowListId);
                                    //                if (flow.Status == (int)COM.OrderInfoStatus.Doing)
                                    //                    nextFlow.Status = (int)COM.OrderInfoStatus.Doing;
                                    //                else if (flow.Status == (int)COM.OrderInfoStatus.Stop)
                                    //                    nextFlow.Status = (int)COM.OrderInfoStatus.Stop;
                                    //            }
                                    //            SOEDAL.Delete(flow);
                                    //            break;
                                    //        }
                                    //    }

                                    //    if (isIn == true)//修改的结点
                                    //    {
                                    //        if (doingTech != null && doingTech.TechID == tech.TechID && IsSetDoingStatus == false)
                                    //        {
                                    //            int flowId = 0;
                                    //            foreach (STProductTech old in oldTechs)
                                    //            {
                                    //                if (tech.TechID == old.TechID)
                                    //                {
                                    //                    flowId = old.WorkFlowListId;
                                    //                    break;
                                    //                }
                                    //            }
                                    //            WorkOrderFlowList flow = SOEDAL.GetFlow(flowId);
                                    //            flow.Status = (int)COM.OrderFlowListStatus.Useable;
                                    //            flow.UserId = tech.UserId;
                                    //            IsSetDoingStatus = true;
                                    //        }
                                    //        else if (IsSetDoingStatus == true)
                                    //        {
                                    //            int flowId = 0;
                                    //            foreach (STProductTech old in oldTechs)
                                    //            {
                                    //                if (tech.TechID == old.TechID)
                                    //                {
                                    //                    flowId = old.WorkFlowListId;
                                    //                    break;
                                    //                }
                                    //            }
                                    //            if (flowId != 0)
                                    //            {
                                    //                WorkOrderFlowList flow = SOEDAL.GetFlow(flowId);
                                    //                flow.Status = (int)COM.OrderFlowListStatus.Wait;
                                    //                flow.UserId = tech.UserId;
                                    //            }
                                    //        }
                                    //    }
                                    //    else if (isIn == false)                  //新增的结点
                                    //    {
                                    //        if (tech.IsNeed == false)
                                    //            continue;
                                    //        WorkOrderFlowList newTech = new WorkOrderFlowList();
                                    //        newTech.AssignTime = DateTime.Now;
                                    //        newTech.PreCompleteTime = DateTime.Now;
                                    //        newTech.CompletedTime = DateTime.Now;
                                    //        newTech.IsEdit = false;
                                    //        //newTech.orderInfo = modifyProduct;
                                    //        newTech.ReceiveTime = DateTime.Now;
                                    //        //if(a==0)
                                    //        //    newTech.Status = (int)COM.OrderFlowListStatus.Useable;
                                    //        //else
                                    //        newTech.Status = (int)COM.OrderFlowListStatus.Wait;
                                    //        newTech.tb_Tech = SOEDAL.GetTechByTechID(tech.TechID);      //流程      
                                    //        newTech.UserId = tech.UserId;                               //节点的默认操作员
                                    //        newTech.WorkOrder = tech.WorkOrder;
                                    //        modifyProduct.WorkOrderFlowList.Add(newTech);
                                    //        if (doingTech != null && doingTech.TechID == tech.TechID && IsSetDoingStatus == false)
                                    //        {
                                    //            newTech.Status = (int)COM.OrderFlowListStatus.Useable;
                                    //            IsSetDoingStatus = true;
                                    //            newTech.UserId = tech.UserId;                           //节点的默认操作员
                                    //        }
                                    //    }




                                    //    if (tech.TechID == 9 && tech.OutShopId != 0)    //设置了默认委外商
                                    //    {
                                    //        //1本身有委外商，则需找出，并修改 2本身无委外商，则需新增委外记录
                                    //        OutProcessRecord opr = SOEDAL.GetOutShopRecord(product.OrderProductId);
                                    //        if (opr != null)                                        //该产品已存在委外记录，则只需修改委外商
                                    //        {
                                    //            opr.OutProcessShop = SOEDAL.GetOutShopByOutShopId(tech.OutShopId);
                                    //        }
                                    //        else                                                    //委外记录还不存在，则需新增
                                    //        {
                                    //            opr = new OutProcessRecord();
                                    //            opr.orderInfo = SOEDAL.GetOrderInfoByOrderProductId(product.OrderProductId);
                                    //            opr.OutProcessShop = SOEDAL.GetOutShopByOutShopId(tech.OutShopId);
                                    //            opr.CreateTime = serverTime;
                                    //            opr.OutRemark = "";
                                    //            opr.PreFetchTime = serverTime;
                                    //            opr.FetchTime = serverTime;
                                    //            opr.FetchRemark = "";
                                    //            opr.users = SOEDAL.GetUserByUserId(editUserId);
                                    //            opr.users1 = SOEDAL.GetUserByUserId(editUserId);
                                    //            opr.Status = (int)COM.OutProcessRecordStatus.OutWaitFenDui;
                                    //            opr.Status2 = (int)COM.OutProcessRecordStatus2.Wait;
                                    //            opr.OperateUser = editUserId;
                                    //        }
                                    //    }
                                    //}
                                    #endregion old

                                    #region new

                                    if (!modifyProduct.WorkOrderFlowList.IsLoaded)
                                    {
                                        modifyProduct.WorkOrderFlowList.Load();
                                    }
                                    product.techs.ForEach(t => t.Status = (int)OrderFlowListStatus.Wait);
                                    product.techs = product.techs.Where(w => w.IsNeed).ToList();

                                    List<WorkOrderFlowList> oldWflList = modifyProduct.WorkOrderFlowList.ToList();
                                    //如果流程没有动
                                    if ((product.techs.Select(w => w.TechID).ToList().Except(oldWflList.Select(w => w.tb_Tech.TechId).ToList())).Count() == 0 && (oldWflList.Select(w => w.tb_Tech.TechId).ToList().Except(product.techs.Select(w => w.TechID).ToList())).Count() == 0)
                                    {

                                    }
                                    else
                                    {
                                        oldWflList = oldWflList.OrderBy(w => w.WorkOrder).ToList();

                                        //找到DOING包括DOING以前的列表

                                        //找到当前的节点
                                        WorkOrderFlowList doingWfl = oldWflList.FirstOrDefault(w => w.Status == (int)OrderFlowListStatus.Useable || w.Status == (int)OrderFlowListStatus.UseableAccept);

                                        //找到DOING包括DOING以前的列表
                                        List<WorkOrderFlowList> beforDoingWflList = oldWflList.Where(w => w.WorkOrder <= doingWfl.WorkOrder).ToList();


                                        //在新的流程里找到DOING以前的都进行付值
                                        foreach (var oldwfl in beforDoingWflList)
                                        {
                                            if (!oldwfl.tb_TechReference.IsLoaded)
                                            {
                                                oldwfl.tb_TechReference.Load();
                                            }
                                            STProductTech wflTemp = product.techs.FirstOrDefault(w => w.TechID == oldwfl.tb_Tech.TechId);
                                            if (wflTemp != null)
                                            {
                                                wflTemp.UserId = oldwfl.UserId;
                                                wflTemp.Status = oldwfl.Status;
                                            }
                                        }

                                        //检查新的流程列表中DOING以前的有没有为STATUS为0的节点
                                        STProductTech newDointTech = product.techs.FirstOrDefault(wf => wf.Status == 1 || wf.Status == 2);
                                        if (newDointTech == null)//如果新流程中没有为DOING的状态的，则将第一个为0的节点改为0                             
                                        {
                                            newDointTech = product.techs.FirstOrDefault(wf => wf.Status == 0);
                                            if (newDointTech != null)
                                            {
                                                newDointTech.Status = (int)OrderFlowListStatus.Useable;
                                            }
                                            else
                                            {
                                                //这时出错了，节点不能全是完成的，完成的产品不能编辑
                                                continue;
                                            }
                                        }

                                        List<STProductTech> listTempList = product.techs.Where(w => w.Status == 0 && w.WorkOrder < newDointTech.WorkOrder).ToList();


                                        if (listTempList.Count > 0)//在当前结点前加了新的节点，则应从新节点处开始
                                        {
                                            STProductTech MinTemp = null;
                                            MinTemp = listTempList.FirstOrDefault(w => w.WorkOrder == listTempList.Min(wt => wt.WorkOrder));
                                            MinTemp.UserId = 0;
                                            MinTemp.Status = 1;
                                            product.techs.Where(w => w.WorkOrder > MinTemp.WorkOrder).ToList().ForEach(w => { w.Status = 0; });
                                        }


                                        //删除原来的节点
                                        foreach (var wfl in oldWflList)
                                        {
                                            db.DeleteObject(wfl);
                                        }

                                        //添加到修改产品中
                                        foreach (var tech in product.techs)
                                        {
                                            WorkOrderFlowList newTech = new WorkOrderFlowList();
                                            newTech.AssignTime = DateTime.Now;
                                            newTech.PreCompleteTime = DateTime.Now;
                                            newTech.CompletedTime = DateTime.Now;
                                            newTech.IsEdit = false;
                                            newTech.ReceiveTime = DateTime.Now;
                                            newTech.Status = tech.Status;
                                            newTech.tb_Tech = db.tb_Tech.First(t=>t.TechId==tech.TechID);      //流程      
                                            newTech.UserId = tech.UserId;                               //节点的默认操作员
                                            newTech.WorkOrder = tech.WorkOrder;
                                            modifyProduct.WorkOrderFlowList.Add(newTech);
                                        }
                                    }



                                    #endregion

                                    STProductTech designTech = product.techs.FirstOrDefault(p => p.IsDesign && p.IsNeed);
                                    double oldAreas = modifyProduct.Area;
                                    int intPageNum = 0;
                                    if (modifyProduct.PageNum == -1)
                                    {
                                        intPageNum = modifyProduct.photoInfo.Count;
                                    }
                                    else
                                    {
                                        intPageNum = modifyProduct.PageNum;
                                    }
                                    if (designTech != null)//设计类的要按产品的算
                                    {
                                        modifyProduct.Area = (modifyProduct.Height * 2.54) * (modifyProduct.Width * 2.54) / 10000 * intPageNum;

                                        switch (modifyProduct.ProductType)
                                        {
                                            case (int)OrderInfoProductType.NoNeedDesignPrint:
                                                modifyProduct.ProductType = (int)OrderInfoProductType.NeedDesignPrint;
                                                break;
                                            case (int)OrderInfoProductType.NoNeedDesignProduct:
                                                modifyProduct.ProductType = (int)OrderInfoProductType.NeedDesignProduct;
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    else
                                    {
                                        modifyProduct.Area = photoAreas;
                                        if (modifyProduct.Area < 0)
                                        {
                                            modifyProduct.Area = -modifyProduct.Area;
                                        }
                                        switch (modifyProduct.ProductType)
                                        {
                                            case (int)OrderInfoProductType.NeedDesignPrint:
                                                modifyProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignPrint;
                                                break;
                                            case (int)OrderInfoProductType.NeedDesignProduct:
                                                modifyProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignProduct;
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    //修改每日开单面积
                                    workFlowListBll.SataShopProductAndOrderAreaForUpdata(modifyProduct.OrderProductId, oldAreas, modifyProduct.Area, db);
                                    // 修改业绩
                                    New_EmployeePerformance nep = new New_EmployeePerformance() { PhotoTotalNum = product.Photos.Count, PreOrderAreas = modifyProduct.Area, OrderArea = modifyProduct.Area, SinglePageNum = modifyProduct.SinglePageNum, MultiplePageNum = modifyProduct.MultiPageNum };

                                    workFlowListBll.NewStatWorkerPerformance(modifyProduct.OrderProductId, -1, nep, db);
                                    #endregion 修改产品
                                }

                            }

                            // WriteLogForCheck.WriteLogFile("开始修改照片");
                            //删除照片
                            foreach (int photoid in DelPhotoIDs)
                            {
                                photoInfo photo = db.photoInfo.First(p=>p.photoId ==photoid);
                                string photoPath = photo.picPath;
                                int pIndex = photoPath.LastIndexOf("\\");
                                string leftStr = photoPath.Substring(0, pIndex + 1);
                                string rightStr = photoPath.Substring(pIndex);
                                string photoBackUpPath = leftStr + "Backup" + rightStr;
                                if (File.Exists(photoBackUpPath))               //删除照片备份
                                    File.Delete(photoBackUpPath);
                                if (File.Exists(photoPath))                     //删除照片
                                {
                                    File.Delete(photoPath);
                                }

                                db.DeleteObject(photo);

                            }
                            //删除产品
                            foreach (int productid in DelProductIDs)
                            {
                                orderInfo product = db.orderInfo.First(o=>o.OrderProductId==productid);
                                //删除本产品内所有的照片
                                //string productPath = product.OrderPath;
                                //if (Directory.Exists(productPath))
                                //    Directory.Delete(productPath, true);

                                //增加商户的预估钱量
                                //double orderInfoPrice = DAL.CommonDAL.TB_OrderBagDAL.GetProductPrice(product.OrderProductId);
                                //double tempBalance = Convert.ToDouble(currentShop.OrderBalance);
                                //currentShop.OrderBalance = Convert.ToDecimal(tempBalance + orderInfoPrice);
                                currentShop.OrderBalance -= product.PrePriceCount;
                                if (currentShop.OrderBalance < 0)
                                {
                                    currentShop.OrderBalance = 0;
                                }
                                product.photoInfo.Load();
                                List<photoInfo> photoList = product.photoInfo.ToList();
                                foreach (photoInfo photo in photoList)
                                {
                                    if (photo.status == (int)COM.PhotoStatus.PingBan)
                                    {
                                        //photo.status = (int)PhotoStatus.DistributedPrinter;
                                        photo.picMakeUp.Load();
                                        picMakeUp picMake = photo.picMakeUp.OrderByDescending(p => p.ID).FirstOrDefault();
                                        if (picMake == null)
                                        {
                                            continue;
                                        }
                                        picMake.BoardReference.Load();
                                        picMake.Board.picMakeUp.Load();
                                        List<picMakeUp> picMakeList = picMake.Board.picMakeUp.ToList(); ;

                                        foreach (picMakeUp picMakeother in picMakeList)
                                        {
                                            picMakeother.photoInfoReference.Load();
                                            photoInfo photoPic = picMakeother.photoInfo;
                                            if (photo.photoId != photoPic.photoId)
                                            {
                                                photoPic.status = (int)PhotoStatus.DistributedPrinter;
                                            }
                                        }


                                        Board deBoard = picMake.Board;
                                        if (deBoard != null)
                                        {
                                            db.DeleteObject(deBoard);
                                        }

                                    }

                                }
                                //SOEDAL.Delete(product);非删除标记删除
                                product.status = (int)OrderInfoStatus.Deleted;
                                //product.Remark = editUser==null?"": editUser.UserName + " 删除时间：" + DateTime.Now + " " + product.Remark;
                                product.Remark += editUser == null ? "" : editUser.UserName + " 删除时间：" + DateTime.Now;
                                List<New_EmployeePerformance> listNEP = OrderBagDAL.GetNEPByOrderId(product.OrderProductId);
                                listNEP.ForEach(p => p.Status = (int)OrderInfoStatus.Deleted);//修改员工的业绩

                                //剪掉每日开单面积
                                workFlowListBll.SataShopProductAndOrderAreaForUpdata(product.OrderProductId, product.Area, -1, db);
                            }

                            db.SaveChanges();

                            //如果删除的照片状态为等待移动，剩下的全是正常的，就将产品状态置为正常生产；如果产品状态都改成了正常，就将订单状态改为正常
                            if (orderBag.Status == (int)COM.OrderBagStatus.WaitPhotoMove)
                            {
                                List<orderInfo> restProduct =db.orderInfo.Where(o=>o.Tb_OrderBag.OrderBagId==orderBagID).ToList();
                                foreach (var item in restProduct)
                                {
                                    if (!item.Tb_ProductReference.IsLoaded)
                                    {
                                        item.Tb_ProductReference.Load();
                                    }
                                }
                                int photoWaitMove = (int)COM.PhotoStatus.WaitPhotoMove;
                                int productWaitMove = (int)COM.PhotoStatus.WaitPhotoMove;
                                bool isExistPhotoNoMove = false;
                                bool isExistProductNoMove = false;
                                bool isAllCompleted = false;//该定单包的产品是否完都完成

                                foreach (orderInfo p in restProduct)
                                {
                                    if (p.status == productWaitMove)        //产品状态为未移动
                                    {

                                        List<photoInfo> restPhoto = p.photoInfo.ToList();
                                        if (restPhoto.Count == 0)
                                        {
                                            p.status = (int)COM.OrderInfoStatus.Doing;
                                            //无照片，产品状态也改为正常
                                            continue;

                                        }
                                        foreach (photoInfo ph in restPhoto)
                                        {
                                            if (ph.status == photoWaitMove)
                                            {
                                                isExistPhotoNoMove = true;
                                                break;
                                            }
                                        }

                                        if (isExistPhotoNoMove == true)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            p.status = (int)COM.OrderInfoStatus.Doing;          //照片全部为正常，产品状态也改为正常
                                        }
                                    }
                                }
                                foreach (orderInfo p in restProduct)
                                {
                                    if (p.status == productWaitMove)
                                    {
                                        isExistProductNoMove = true;
                                        break;
                                    }

                                    if (p.status != (int)OrderInfoStatus.Completed)
                                    {
                                        isAllCompleted = false;
                                        break;
                                    }
                                }


                                if (isExistProductNoMove == false)                              //不存在产品状态为等待移动，就修改订单状态
                                {
                                    orderBag.Status = (int)COM.OrderBagStatus.Doing;
                                }
                                if (isAllCompleted)
                                {
                                    orderBag.Status = (int)COM.OrderBagStatus.Completed;
                                    //并移动历史数据...
                                    isNeedMoveThisBag = true;
                                }
                            }

                            //更新
                            foreach (orderInfo item in addProductInfo)
                            {
                                item.OrderProductCode = "2" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));

                                //更新业绩和开单面积
                                workFlowListBll.SataShopProductAndOrderAreaForUpdata(item.OrderProductId, -1, item.Area,db);
                                //workFlowListBll.NewStatWorkerPerformance(item.OrderProductId,
                            }
                            foreach (photoInfo item in addPhotoInfo)
                            {
                                item.PhotoBarCode = "3" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                            }
                            db.SaveChanges();

                            tran.Commit();

                        }
                        catch (Exception ex)
                        {
                            //foreach (photoInfo photo in addPhotoInfo)
                            //{
                            //    SOEDAL.Delete(photo);
                            //}
                            //foreach (orderInfo product in addProductInfo)
                            //{
                            //    SOEDAL.Delete(product);
                            //}
                            ////tran.Rollback();
                            //if (SOEDAL.DataEntites.Connection.State != ConnectionState.Closed)
                            //{
                            //    SOEDAL.DataEntites.Connection.Close();
                            //}
                            tran.Rollback();
                            WriteLogForCheck.WriteLogFile(ex.StackTrace);
                            throw ex;
                        }
                        if (isNeedMoveThisBag)
                        {
                            DataMaintenance.MoveHistoryData(orderBagID);
                        }
                        //统计开单员业绩
                        double tempArea = 0;
                        ///修正最新的照片面积

                        foreach (WorkOrderFlowList flow in startOrderFlows)
                        {
                            //workFlowListBll.StatWorkerPerfmance(flow, SOEDAL.DataEntites, out tempArea);
                            workFlowListBll.NewStatWorkerPerformance(flow, db);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //断网时，保存已经移动了的照片路径 
                DataTable DTTempTarPath = CreateTempTarPathDT();
                foreach (string s in PhotoTemps)
                {
                    DTTempTarPath.Rows.Add(s);
                }
                foreach (string s in MovedTarPaths)
                {
                    DTTempTarPath.Rows.Add(s);
                }
                
                DTTempTarPath.WriteXml("XmlTarPathEdit.xml");
                throw ex;
            }
        }
        #endregion

        #region 原产品的当前节点在新产品模板中存在
        /// <summary>
        /// 原产品的当前节点在新产品模板中存在
        /// </summary>
        /// <param name="oldProductId"></param>
        /// <param name="newProductId"></param>
        /// <returns></returns>
        public bool IsOldCurrentTechInNewProduct(int oldProductId, int newProductId)
        {
            try
            {
                int OldPreTechId = SOEDAL.GetOrderProductCurrentTech(oldProductId);
                if (OldPreTechId == -1)             //原产品已经完成
                    return false;
                return SOEDAL.IsTechExist(OldPreTechId, newProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取产品当前流程的上一个流程
        /// <summary>
        /// 获取产品当前流程的上一个流程
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetCurrentTechId(int orderProductId)
        {
            try
            {
                return SOEDAL.GetOrderProductCurrentTech(orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 编辑的产品对象(订单包的组成单位)
        /// <summary>
        /// 产品对象
        /// </summary>
        public class ProductInfoEdit
        {
            public int ProductSerialID { get; set; }            //产品系列ID，用于新增产品的区分
            public int OrderProductId { get; set; }              //订单产品ID，用于已存在产品的区分
            public int ProductID { get; set; }                  //产品ID(可能会有重复的ID)
            public int newProductId { get; set; }               //修改产品类型时，新产品类型Id

            public List<STPhotoEdit> Photos { get; set; }           //产品的照片集合
            public List<STProductTech> techs { get; set; }      //产品的流程
            public string ProductBarCode { get; set; }          //产品编码
            public string ProductName { get; set; }             //产品名称
            public string CtmName { get; set; }                 //客户名称
            public int ProductNum { get; set; }                 //产品份数
            public int PageNum { get; set; }                    //Page数
            //public int PaperTypeID { get; set; }                //纸型ID
            //public string PaperTypeName { get; set; }           //纸型名称
            //public string PaperFaceName { get; set; }           //纸面名称
            //public int PaperFaceID { get; set; }                //纸面ID
            public float Height { get; set; }                   //产品高
            public float Width { get; set; }                    //产品宽
            public string Unit { get; set; }                    //产品的单位,用于随单位的变化的显示
            public string ProductRemark { get; set; }           //产品备注
            public int ProductTypeCode { get; set; }       //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印0 不含照片的产品
            public bool IsCheckStyle { get; set; }              //当产品为设计的产品的时候检查产品的尺寸和page数
            public int PhotoNum { get; set; }                   //照片数量
            public float PhotoAllArea { get; set; }             //产品内照片总面积
            public string OrilOrderPath { get; set; }           //产品内照片的原始目录
            public int ProductType { get; set; }                //产品的类型 1新增 2修改 3删除 4未改变
            public int DoingTechId { get; set; }                //当前流程节点的上一个节点Id
            public int Status { get; set; }                     //产品状态 暂停状态不可编辑
            public int PrinterId { get; set; }                  //打印机Id
            public int OrderType { get; set; }
            //一下属性用于跟照片联动
            private int _paperTypeID;
            public int PaperTypeID
            {
                get { return _paperTypeID; }
                set
                {
                    _paperTypeID = value;
                    if (Photos != null && Photos.Count > 0)
                    {
                        Photos.ForEach(p => p.PaperTypeID = value);
                    }
                }
            }
            private string _paperTypeName;
            public string PaperTypeName
            {
                get { return _paperTypeName; }
                set
                {
                    _paperTypeName = value;
                    if (Photos != null && Photos.Count > 0)
                    {
                        Photos.ForEach(p => p.PaperTypeName = value);
                    }
                }
            }
            private int _paperFaceID;
            public int PaperFaceID
            {
                get { return _paperFaceID; }
                set
                {
                    _paperFaceID = value;
                    if (Photos != null && Photos.Count > 0)
                    {
                        Photos.ForEach(p => p.PaperFaceID = value);
                    }
                }
            }
            private String _paperFaceName;
            public string PaperFaceName
            {
                get { return _paperFaceName; }
                set
                {
                    _paperFaceName = value;
                    if (Photos != null && Photos.Count > 0)
                    {
                        Photos.ForEach(p => p.PaperFaceName = value);
                    }
                }
            }
            public string StringCostItems { get; set; }//收费项目

        }
        #endregion

        #region 订单包头信息
        public struct STOrderBagTitle
        {
            public string OrderBagCode { get; set; }
            public int OrderID { get; set; }
            public string OrderName { get; set; }
            public int OrderPriority { get; set; }
            public string ShopName { get; set; }
            public DateTime OrderTime { get; set; }
            public DateTime PreCompleteTime { get; set; }       //指定完成时间
            public string OrderRemark { get; set; }
        }
        #endregion
        #region 照片结构(编辑)
        /// <summary>
        /// 照片的结构
        /// </summary>
        public class STPhotoEdit
        {
            public int PhotoID { get; set; }                    //照片ID(等于-1表示是新增的)
            public string PhotoFullPath { get; set; }           //照片的全路径
            public string PhotoName { get; set; }               //照片名称
            public string PhotoSize { get; set; }               //照片大小
            public int PhotoDPI { get; set; }                   //照片分辨率
            public float PhotoStandardHCompute { get; set; }    //标准高,用于计算
            public float PhotoStandardWCompute { get; set; }    //标准宽,用于计算
            public string PhotoHWStandard { get; set; }         //标准高宽
            public string PhotoAreaStandard { get; set; }       //标准面积
            public string PhotoHW { get; set; }                 //高宽
            public int PixHeight { get; set; }                  //像素高
            public int PixWidth { get; set; }                   //像素宽
            public string PhotoArea { get; set; }               //面积
            public string Unit { get; set; }                    //单位(在非设计类产品单位变化时使用)
            public string PhotoRemark { get; set; }             //照片备注
            public bool Selected { get; set; }                  //照片是否被选中
            public int PhotoType { get; set; }                  //照片类型 1新增 2修改 3删除 4未改变
            public bool IsPiPei { get; set; }                   //当产品是不需要设计的产品时，照片是否与产品尺寸匹配
            public bool IsModifySize { get; set; }              //照片是否修改了尺寸
            public int PhotoNum { get; set; }                   //照片数量
            public int PaperTypeID { get; set; }                //纸型ID
            public string PaperTypeName { get; set; }           //纸型名称
            public string PaperFaceName { get; set; }           //纸面名称
            public int PaperFaceID { get; set; }                //纸面ID
        }
        #endregion

        #region 照片移动到本地已开单，保存原路径与已开单路径，便于在出错后回退
        /// <summary>
        /// 照片移动到本地已开单
        /// </summary>
        public class PhotoMoveTemp
        {
            public PhotoMoveTemp(string s, string t)
            {
                src = s;
                tar = t;
            }
            public string src;
            public string tar;
        }
        /// <summary>
        /// 断网时保存在本地的，已移动到本地“已开单”目录下的照片路径
        /// </summary>
        /// <returns></returns>
        public DataTable CreateTempTarPathDT()
        {
            DataTable dt = new DataTable();
            dt.TableName = "TableTempTarPath";
            dt.Columns.Add("TarPath", typeof(string));
            return dt;
        }
        #endregion

        #region 刷新指定的产品集合
        /// <summary>
        /// 刷新指定的产品集合
        /// </summary>
        /// <param name="obj"></param>
        public void RefreshPhotoinfo(object obj)
        {
            try
            {
                SODAL.RefreshPhotoinfo(obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 是否存在还未移动完的照片
        /// <summary>
        /// 是否存在还未移动完的照片
        /// </summary>
        public bool PhotoMoveCompleted(int orderBagId)
        {
            try
            {
                return SOEDAL.PhotoMoveCompleted(orderBagId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //------------------------------------------------------------------
        //---------------------------修改产品类型---------------------------
        //------------------------------------------------------------------

        #region 获取所有流程节点
        /// <summary>
        /// 获取所有流程节点
        /// </summary>
        /// <returns></returns>
        public List<STProductTech> GetAllFlowTechs()
        {
            try
            {
                List<tb_Tech> dtechs = SOEDAL.GetAllTech();
                List<STProductTech> techs = new List<STProductTech>();
                foreach (tb_Tech t in dtechs)
                {
                    STProductTech st = new STProductTech();
                    if (st.TechName == "开始")
                        continue;
                    st.TechID = t.TechId;
                    st.TechName = t.TechName;
                    techs.Add(st);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public void ModifyProductType(int orderProductId, ProductInfoEdit product, int doingTechId)
        {
            try
            {
                System.Transactions.TransactionOptions options = new TransactionOptions();
                options.Timeout = new TimeSpan(0, 0, 600);
                options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {
                    orderInfo info = SOEDAL.GetProductByOrderProductID(orderProductId);
                    info.OrderProductName = product.ProductName;
                    info.PageNum = product.PageNum;
                    info.Remark = product.ProductRemark;
                    Tb_Product modelProduct = SOEDAL.GetProductByProductID(product.ProductID);
                    info.Tb_Product = modelProduct;
                    info.Width = product.Width;
                    //先删除原来的流程
                    List<WorkOrderFlowList> orderInfoFlows = SOEDAL.GetProductTechs(orderProductId);
                    foreach (WorkOrderFlowList flow in orderInfoFlows)
                    {
                        SOEDAL.Delete(flow);
                    }
                    //添加新流程
                    List<STProductTech> workTechs = product.techs;
                    workTechs.Sort(CompareTechASC);         //按WorkOrder排序
                    int j = 0;
                    DateTime lastTechTime = DateTime.Now;                //上个节点的完成时间
                    foreach (STProductTech tech in workTechs)
                    {
                        if (tech.IsNeed == false)                           //当前产品不需要该结点
                            continue;
                        WorkOrderFlowList work = new WorkOrderFlowList();
                        work.tb_Tech = SODAL.GetTechByTechID(tech.TechID);
                        double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                        work.IsEdit = false;
                        if (j == 0)
                        {
                            work.Status = (int)COM.OrderFlowListStatus.Complete;
                            //work.UserId = userId;
                        }
                        else if (j == 1)
                        {
                            work.Status = (int)COM.OrderFlowListStatus.Useable;
                            work.UserId = 0;
                        }
                        else
                        {
                            work.Status = (int)COM.OrderFlowListStatus.Wait;
                            work.UserId = 0;
                        }
                        work.AssignTime = lastTechTime;
                        work.ReceiveTime = lastTechTime;
                        work.PreCompleteTime = Convert.ToDateTime(work.ReceiveTime).AddHours(techNeedTime);
                        work.CompletedTime = work.PreCompleteTime;
                        lastTechTime = Convert.ToDateTime(work.CompletedTime);
                        work.WorkOrder = tech.WorkOrder;
                        j++;
                    }
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //---------------------------------------------------------------------
        //-----------------------------CRC码-----------------------------------
        //---------------------------------------------------------------------
        #region 加载最近2天的CRC码
        public List<string> GetCRCMark()
        {
            try
            {
                return SODAL.GetCRCMark();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 取到所有的收费项目
        /// </summary>
        /// <returns></returns>
        public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> GetAllCostItems()
        {
            List<CommonChargeItem> items = SODAL.GetAllCostItems();
            List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> itemList = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();
            foreach (CommonChargeItem item in items)
            {
                MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo = new MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO();
                ddo.CommonChargeItemId = item.CommonChargeItemId;
                ddo.ItemName = item.ItemName;
                itemList.Add(ddo);
            }
            listAllCostItems = itemList;
            return itemList;
        }
        /// <summary>
        /// 取到所有的收费项目
        /// </summary>
        /// <returns></returns>
        public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> GetShopCostItems(int inShopId)
        {
            List<CommonChargeItem> items = SODAL.GetShopCostItems(inShopId);
            List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> itemList = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();
            if (items != null)
            {
                foreach (CommonChargeItem item in items)
                {
                    MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo =
                        new MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO();
                    ddo.CommonChargeItemId = item.CommonChargeItemId;
                    ddo.ItemName = item.ItemName;
                    itemList.Add(ddo);
                }
            }
            listAllCostItems = itemList;
            return itemList;
        }
        /// <summary>
        /// 取到所有的收费项目
        /// </summary>
        /// <returns></returns>
        public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> GetShopCostItems(string inShopName)
        {
            List<CommonChargeItem> items = SODAL.GetShopCostItems(inShopName);
            List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> itemList = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();
            if (items != null)
            {
                foreach (CommonChargeItem item in items)
                {
                    MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo =
                        new MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO();
                    ddo.CommonChargeItemId = item.CommonChargeItemId;
                    ddo.ItemName = item.ItemName;
                    itemList.Add(ddo);
                }
            }
            listAllCostItems = itemList;
            return itemList;
        }
        private static List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> listAllCostItems = new List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO>();

        /// 获取所有流程节点
        /// </summary>
        /// <returns></returns>
        public List<STProductTech> GetAllFlowTechBeforPrint()
        {
            try
            {
                List<tb_Tech> dtechs = SOEDAL.GetAllTech();
                List<STProductTech> techs = new List<STProductTech>();
                int intTechType = (int)TechType.print;
                tb_Tech printTech = dtechs.FirstOrDefault(p => p.TechType == intTechType);
                foreach (tb_Tech t in dtechs.Where(p => p.WokerOrder < printTech.WokerOrder))
                {
                    STProductTech st = new STProductTech();
                    if (st.TechName == "开始")
                        continue;
                    st.TechID = t.TechId;
                    st.TechName = t.TechName;
                    st.WorkOrder = t.WokerOrder;
                    st.IsNessesary = t.IsNecessary;
                    st.NeedTime = t.NeedTime;
                    st.Techtype = t.TechType;
                    st.IsDesign = t.IsDesign;
                    string ccis = "";
                    //newTech.ListCommon=new List<CommonChargeItem_info>;
                    //加载节点附带的收费项目
                    if (!t.CommonChargeItem.IsLoaded)
                    {
                        t.CommonChargeItem.Load();
                    }
                    List<CommonChargeItem> listCCI = t.CommonChargeItem.ToList();
                    foreach (CommonChargeItem cci in listCCI)
                    {
                        ccis += cci.ItemName + ",";
                    }
                    st.CommonChargeItems = ccis.Trim(',');
                    techs.Add(st);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<STPaperType> GetShopPaperType(int inShopId)
        {
            List<STPaperType> rtnList = new List<STPaperType>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Shop shop = db.Shop.FirstOrDefault(p => p.ShopId == inShopId);
                shop.Shop_Paper_Price.Load();
                foreach (Shop_Paper_Price spp in shop.Shop_Paper_Price)
                {
                    spp.paperTypeReference.Load();
                    STPaperType papertype = new STPaperType() { PaperTypeID = spp.paperType.PaperTypeID, PaperTypeName = spp.paperType.Name };
                    rtnList.Add(papertype);
                }

            }
            return rtnList;
        }
        public List<STPaperType> GetShopPaperType(string inShopName)
        {
            List<STPaperType> rtnList = new List<STPaperType>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Shop shop = db.Shop.FirstOrDefault(p => p.shopName == inShopName);
                shop.Shop_Paper_Price.Load();
                foreach (Shop_Paper_Price spp in shop.Shop_Paper_Price)
                {
                    spp.paperTypeReference.Load();
                    STPaperType papertype = new STPaperType() { PaperTypeID = spp.paperType.PaperTypeID, PaperTypeName = spp.paperType.Name };
                    rtnList.Add(papertype);
                }

            }
            return rtnList;
        }

        private string[] GetFilesPath(string dirPath)
        {
            string[] file1 = Directory.GetFiles(dirPath, "*.jpg");
            string[] file2 = Directory.GetFiles(dirPath, "*.tif");
            string[] file3 = Directory.GetFiles(dirPath, "*.jpeg");
            string[] file4 = Directory.GetFiles(dirPath, "*.tiff");
            string[] files = file1.Concat(file2).Concat(file3).Concat(file4).ToArray();
            return files;
        }

        private FileInfo[] GetFileInfo(string dirPath)
        {
            DirectoryInfo ssubInfo = new DirectoryInfo(dirPath);
            FileInfo[] sssfile1 = ssubInfo.GetFiles("*.jpg");
            FileInfo[] sssfile2 = ssubInfo.GetFiles("*.tif");
            FileInfo[] sssfile3 = ssubInfo.GetFiles("*.jpeg");
            FileInfo[] sssfile4 = ssubInfo.GetFiles("*.tiff");
            FileInfo[] sssfile = sssfile1.Concat(sssfile2).Concat(sssfile3).Concat(sssfile4).ToArray();
            return sssfile;
        }
    }
    public class ProductCommonItem
    {
        public int ProductID { get; set; }
        public int CommonID { get; set; }
        public string ItemName { get; set; }
    }

}
